1. 背景
npm 3.0.0之后package.json的engineStrict属性就不支持了,
This feature was removed in npm 3.0.0
Prior to npm 3.0.0, this feature was used to treat this package as if the user had set engine-strict. It is no longer used.
这样engines属性也就不支持了,
Unless the user has set the engine-strict config flag, this field is advisory only and will only produce warnings when your package is installed as a dependency.
因此就没办法指定模块的运行时node版本了。
不过我们还可以采用下面的办法实现。
2. 指定运行时node版本
2.1 先使用nvm安装最新的node LTS版本
$ nvm install --lts
$ node --version
10.14.1
$ npm --version
6.4.1
2.2 新建项目
$ npm init -f
2.3 安装指定的node版本作为devDependencies
$ npm i -S node@4.2.0
它会安装一个node@4.2.0模块到node_modules中,
并设置node_modules/.bin/node软链接到node_modules/node/bin/node。
$ tree -L 4 -a
.
├── node_modules
│ ├── .DS_Store
│ ├── .bin
│ │ └── node -> ../node/bin/node
│ ├── node
│ │ ├── .DS_Store
│ │ ├── README.md
│ │ ├── bin
│ │ │ └── node
│ │ ├── installArchSpecificPackage.js
│ │ ├── node_modules
│ │ │ ├── .bin
│ │ │ └── node-darwin-x64
│ │ └── package.json
│ └── node-bin-setup
│ ├── index.js
│ └── package.json
├── package-lock.json
└── package.json
2.4 新建源码文件index.js
let a = 1;
2.5 使用npx调用.bin中的命令
$ npx node index.js
~/Test/test-node/index.js:1
(function (exports, require, module, __filename, __dirname) { let a = 1;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
我们发现它报错了,
这是因为node@4.2.0不支持let
,相关的issue可以参考这里。
3. npx
3.1 node_modules/.bin
npx是npm 5.2.0之后,默认全局安装的命令行工具,
它提供了一个简单的方式来调用node_modules/.bin下面的命令。
Executes <command> either from a local node_modules/.bin, or from a central cache, installing any packages needed in order for <command> to run.
By default, npx will check whether <command> exists in $PATH, or in the local project binaries, and execute that. If <command> is not found, it will be installed prior to execution.
有了npx
,我们甚至还可以一条命令直接启动一个http-server,
$ npx http-server
npx: 25 安装成功,用时 8.057 秒
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://10.15.230.10:8080
Hit CTRL-C to stop the server
npx
会临时安装一个http-server模块,
并执行http-server模块中/.bin/
文件夹中的http-server命令,
npx
执行完后,临时的http-server模块会被删掉。
$ which http-server
http-server not found
3.2 npm scripts
如果不用npx
,我们就得将命令加入到npm scripts中,例如,
{
...
"scripts": {
"dev": "node index.js"
},
...
}
然后使用npm-run-script方式调用,
$ npm run dev
npm run
会自动添加node_module/.bin
到当前命令所用的PATH
变量中。
参考
engines
engineStrict
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
网友评论