This can be achieved by including a couple of additional packages in your project.
Additional packages
Install http-server:
$ npm install http-server --save-dev
and concurrently:
$ npm install concurrently --save-dev
npm scripts
Add the following open
script to package.json
:
"scripts": {
"start": "npm run open",
"open": "concurrently \"http-server -a localhost -p 1234\" \"open http://localhost:1234/build\""
}
Note
start
will actually be defined as follows to include the tasks you currently have:
"start": "npm run build && npm run dev && npm run open",
The code in the open
script above which reads:
open http://localhost:1234/build
...assumes that the build
task you have previously defined outputs a index.html
to a build
folder. If the file is named differently you will need to define it. E.g.
open http://localhost:1234/build/the_html_file_name.html
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:
$ npm install sleep-ms --save-dev
and change the open
script to:
"open": "concurrently \"http-server -a localhost -p 1234\" \"sleepms 1000 && open http://localhost:1234/build\""
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
and opn-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 the opener
or opn-cli
packages.
Essentially only the http-server
package is necessary and the npm script required now is:
"open": "http-server build -a localhost -p 1234 -o"