首页 > 代码库 > [NPM] Create a node script to replace a complex npm script
[NPM] Create a node script to replace a complex npm script
In this lesson we will look at pulling out complex npm script logic into an external JavaScript file. Instead of writing bash scripts you can leverage your JavaScript abilities to automate your build process. We’ll use some helper node modules such as shelljs, opn-cli, and babel-cli.
Install:
npm i -D shelljs babel-cli
From:
"test": "BABEL_ENV=test mocha spec/ --require babel-register",
To:
1. create a "scripts/test.js" file.
2. Add content:
import { exec } from "shelljs";const isWindows = process.platform === "win32";const environment = isWindows ? "set BABEL_ENV=test&&" : "BABEL_ENV=test";exec( `${ environment } mocha spec/ --require babel-register` );
3. Change package.json
"test": "babel-node ./scripts/test.js",
From:
"build": "npm-run-all build:*", "prebuild": "rm -rf public/$npm_package_version", "build:html": "pug --obj data.json src/index.pug --out public/$npm_package_version/", "build:css": "node-sass src/index.scss | postcss -c .postcssrc.json | cssmin > public/$npm_package_version/index.min.css", "build:js": "mustache data.json src/index.mustache.js | uglifyjs > public/$npm_package_version/index.min.js",
To:
1. create "scripts/build.js".
2. Add content:
import { rm, exec } from "shelljs";const version = process.env.npm_package_version;rm( "-rf", `public/${ version }` );exec( `pug --obj data.json src/index.pug --out public/${ version }/` );exec( `node-sass src/index.scss | postcss -c .postcssrc.json | cssmin > public/${ version }/index.min.css` );exec( `mustache data.json src/index.mustache.js | uglifyjs > public/${ version }/index.min.js` );
3. Change package.json:
"build": "babel-node ./scripts/build.js",
From:
"server": "npm-run-all --parallel server:*", "server:create": "http-server public/$npm_package_version -p $npm_package_config_port", "server:launch": "open http://localhost:$npm_package_config_port",
To:
1. Create "scripts/server.js".
2. Add content:
import { exec } from "shelljs";const { npm_package_version: version, npm_package_config_port: port} = process.env;exec( `http-server public/${ version } -p ${ port }`, { async: true } );exec( `opn http://localhost:${ port }` );
3. Change package.json file:
"server": "babel-node ./scripts/server.js",
Be careful that in Windows single quote doesn‘t work, we need to replace single quote to
\"
[NPM] Create a node script to replace a complex npm script
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。