I've been trying to figure out how to write a npm script
that will culminate with the application being launched in the user's browser without them having to manually open the browser and go to localhost:1234
.
Right now my script reads as:
"start": "npm run build && npm run dev",
"build": "npm run clean && npm run mkdir && npm run build:html && npm run build:css && npm run build:js",
"dev": "webpack-dev-server --inline --hot --content-base build --history-api-fallback",
Wanting to add "open": <some code here>,
So when someone goes to GitHub and clones or forks off my repository they are given the instructions for how to run the application. I just thought that automating this would be a nice little addition.
Anyone know how this is possible? I'm pretty sure it is and think it has something to do with calling a command in bash. Thanks in advance for the help!
If You use Webpack There is another way to do this using the
webpack-dev-server
npm install webpack-dev-server --save-dev
Then run
webpack-dev-server
or configurenpm script
like this :"start": "webpack-dev-server"
Then navigate to
http://localhost:8080
It serve per default files in the current directory. If you want to serve files from another directory you need to use the
--content-base
option like this:More about webpack-dev-server here in the official webpack doc.
This can be achieved by including a couple of additional packages in your project.
Additional packages
Install http-server:
and concurrently:
npm scripts
Add the following
open
script topackage.json
:Note
start
will actually be defined as follows to include the tasks you currently have:The code in the
open
script above which reads:...assumes that the
build
task you have previously defined outputs aindex.html
to abuild
folder. If the file is named differently you will need to define it. E.g.You may need to add a delay between launching the server and opening the file, just to wait a bit til the server starts up. If that's the case then also install sleep-ms:
and change the
open
script to:Cross platform
Unfortunately, the open command is not supported cross-platform. To overcome this issue check out opener or opn-cli and replace the command accordingly.
However, both packages, (
opener
andopn-cli
), utilize Object.assign() so will not run in older versions of nodejs.Edit: To open a browser window after starting the server,
http-server
now accepts the-o
option . This can be utilized instead of either theopener
oropn-cli
packages.You just need :
(I tested in Windows 10 .)
The scripts you need is :
But you should pay attention that , in Windows 10 , you must place " start http://localhost:1234 " before your node.js server begins .
Hope to help you .
For Webpack users: OpenBrowserPlugin does the trick too!
Install one dependency:
And add this in webpack config file: