[NPM] Create a node script to replace a complex npm script

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

Create-react-app npm run build 太慢了

npm install 在“eb create”节点 6.2.2 上失败

npm 错误! 404 未找到 - 获取 https://registry.npmjs.org/create-myreactnativeapp - 未找到

create-react-app 创建的项目执行npm run eject后,运行报错

node-npm发布包-package.json中bin的用法

安装React基本运行环境