41

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!

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
rockchalkwushock
  • 1,143
  • 2
  • 9
  • 19
  • 1
    Perhaps you can clarify to help improve your chances of obtaining an answer... **1**) When someone types `npm run open` via their CLI do you intend the command to launch _"the instructions for how to run the application"_ which is for example: `instructions.html`, (residing in the project folder), in their default browser at: `localhost:1234`? **2**) Or, should `npm run open` proceed to open the applications `index.html` at `localhost:1234`. If the answer to **1** is yes - does it have to be from `localhost:1234` or will simply opening `instructions.html` in the browser suffice? – RobC Dec 19 '16 at 14:41
  • @RobC my fault I did write that somewhat vaguely. What I'm aiming at is writing a script that will open the application in the user's browser (my guess is the OS would do so on the user's default browser). So the `start` script would first execute a `build` then fire up the server running on `localhost:1234` and finally `open` the application in the user's browser, hosting on `localhost:1234`. My guess is that the `open` script will need to be shell commands to do such. – rockchalkwushock Dec 21 '16 at 05:38

11 Answers11

52

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

  1. start will actually be defined as follows to include the tasks you currently have:

     "start": "npm run build && npm run dev && npm run open",
    
  2. 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
    
  3. 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"
RobC
  • 22,977
  • 20
  • 73
  • 80
  • Does the `-o` option mean you no longer need `concurrently` since it's just `http-server` as single task remaining now? – LWChris Aug 16 '23 at 03:14
  • @LWChris - yes that's correct, the `-o` option effectively makes `concurrently` redundant. The npm script required is: `"open": "http-server build -a localhost -p 1234 -o"` This expects a `index.html` file to exist in the `build` folder that is located at the root of your project directory. – RobC Aug 19 '23 at 11:17
28

You just need:
start http://localhost:1234 (I tested in Windows 10).

The scripts you need is :
"open": "start http://localhost:1234"

But you should pay attention that, in Windows 10, you must place start http://localhost:1234 before your node.js server begins.

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
Lancer.Yan
  • 857
  • 13
  • 10
8

For Webpack users: OpenBrowserPlugin does the trick too!

Install one dependency:

npm install open-browser-webpack-plugin --save-dev

And add this in webpack config file:

var OpenBrowserPlugin = require('open-browser-webpack-plugin');

...

plugins: [
  new OpenBrowserPlugin({ url: 'http://localhost:3000' })
]

Update (may 2019)

Please note OpenBrowserPlugin is abandoned and a severe vulnerability hasn't been fixed for a while. However rodrigopandini has forked it here. Use npm install rodrigopandini/open-browser-webpack-plugin to use it.

Made in Moon
  • 2,294
  • 17
  • 21
  • 1
    Please note [OpenBrowserPlugin](https://github.com/baldore/open-browser-webpack-plugin) is abandoned and a severe vulnerability hasn't been fixed for a while. However [rodrigopandini](https://github.com/rodrigopandini) has forked it [here](https://github.com/rodrigopandini/open-browser-webpack-plugin). Use `npm install rodrigopandini/open-browser-webpack-plugin` to use it. – Mausam May 03 '19 at 08:50
2
var express = require('express');
var app = express();

var server = app.listen(process.env.PORT || 5000, function() {
  var port = server.address().port;
  var url = `http://localhost:${port}`;

  var start =
    process.platform == "darwin"
      ? "open"
      : process.platform == "win32"
      ? "start"
      : "xdg-open";
  require("child_process").exec(start + " " + url);
  console.log("App now running on port", port);
});
Joe Shakely
  • 623
  • 7
  • 9
1

If You use Webpack There is another way to do this using the webpack-dev-server

  • Install it using npm install webpack-dev-server --save-dev
  • Then run webpack-dev-server or configure npm 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:

webpack-dev-server --content-base thefolderyouwanttoserve/

More about webpack-dev-server here in the official webpack doc.

billyjov
  • 2,778
  • 19
  • 35
1

Command to open URL (no extention or library needed) is:

"script_name": "start http://localhost:8080"


Put it with other commands:

"script_name": "set Node_ENV=development& start http://localhost:8080& nodemon app.js"

*NOTE: don't put it after node or nodemon command, otherwise it will not work.


Additional info:
  • It will open the URL in default browser.

  • First in browser it may show failed to load, because it takes some time for server to run. But it will refresh automatically when server will start if not then just refresh manually.

Rajan
  • 625
  • 7
  • 19
1

Change

"start": "npm run build && npm run dev",

to

"start": "open http://localhost:3000 && npm run build && npm run dev",

Works on macOS. You might need to refresh browser window after server has started.

1

Simply add the http-server to your project using

npm i http-server --save-exact

and then add the following script:

"scripts": {
    "start": "npm run open",
    "open": "http-server public -a localhost -p 1234 -o"
  },

to your package.json where

  • "public" is the subfolder or path to serve
  • the option -a gives the server
  • the option -p provides the port
  • and the option -o opens the browser
astares
  • 11
  • 1
0

For macOS users, I've managed a way to do this:

  1. Install Opener (npm i opener)
  2. Go to package.json file.
  3. Create a new script. In my case, I named it like this (I was using port 9000, just change it depending on your preferences): "test": "opener http://localhost:9000"
  4. Run npm test in your console and localhost:9000 will pop in your browser.
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
pelayotrives
  • 141
  • 1
  • 5
0

I just came across this question and wanted to add my view so that it might help someone

after installing webpack-dev-server

change your start script as follows

"start": "webpack-dev-server --open"

I believe this should take you to the browser directly

0

If you already know the portal eg. 4200 then, following steps can work too.

  1. using your terminal , cd into the project (frontend) directory
  2. npm install
  3. git checkout <expected branch>
  4. npm run start
  5. on successful compilation message in terminal, open the browser with http://localhost:4200/
Harsha
  • 17
  • 1
  • 1
  • 6