b.stevens.photo
b.stevens.photo

Reputation: 934

Opening a html file in the browser from npm script

All I can find for this are solutions that require installing an npm package that will start up an http server for hosting the file. My only requirement however is opening a very simple generated html file from the local computer into the browser via a npm script, no server required, is this doable without a package?

Upvotes: 7

Views: 16250

Answers (5)

Shawinder Jit Singh
Shawinder Jit Singh

Reputation: 143

 {   "start": "start http://localhost:8000 & npm run dev", }

just use above script this works for me. first it will open url in browser and then launch the server. issue is first url will throw error and then after runing sever page wil be auto reload.

This is better if you dont need to use any external package.

Upvotes: 1

Allan Andrade
Allan Andrade

Reputation: 710

I tried the Daniel's answer, but it does not works to me.

Based on his answer, I found the open-cli package.

npm i -D open-cli

and use it (open-cli) in package.json script object like so

{
  "name": "somename",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "open-my-html": "open-cli path/to/your/index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies: {
    "open-cli": "^6.0.1"
  },
  "author": "",
  "license": "ISC"
}

then run

npm run open-my-html

Now it works opening the html file on default browser.

Upvotes: 5

Daniel
Daniel

Reputation: 59

the easiest way to do this is to install the open package

npm i open --save-dev

and use it in package.json script object like so

{
  "name": "somename",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "open-my-html": "open path/to/your/index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies: {
    "open": "^7.3.0"
  },
  "author": "",
  "license": "ISC"
}

then run

npm run open-my-html

Upvotes: 0

abhnv42
abhnv42

Reputation: 33

Supposing that your node script and index.html are in the same folder

const open = require('open');

(async () => {
        await open('index.html', {"wait": true });
})();

Take a look at this package: https://www.npmjs.com/package/open

Upvotes: 1

b.stevens.photo
b.stevens.photo

Reputation: 934

Found that I could create a bash script with contents

#!/bin/bash
start chrome "$(realpath "./jest/report.html")"

And then run that using

"test": "jest && bash ./open-browser.sh"

Upvotes: 1

Related Questions