如何在启用 ES6 功能的情况下运行 Node.js 应用程序? [英] How to run Node.js app with ES6 features enabled?
问题描述
我使用require hook.io/" rel="noreferrer">BabelJS(以前称为 6to5)以运行带有 es6features 的节点应用程序:
I use the require hook of BabelJS (formerly named 6to5) to run node apps with es6features:
// run.js
require("babel/register");
require("./app.js6");
我调用 node run.js
来运行我的 app.js6.我需要安装 BabelJS 并为我想使用 es6features 的每个项目提供一个 run.js.我更喜欢像 nodejs6 app.js6
这样的调用.如何独立实现这个系统(Unix和Windows)?
I call node run.js
to run my app.js6. I need to install BabelJS and provide a run.js for each project I'd like to use es6features. I would prefer a call like nodejs6 app.js6
. How can I achieve this system independently (Unix and Windows)?
推荐答案
将 babel-cli
和 babel-preset-es2015
(又名 ES6)依赖项添加到您的应用程序的package.json 文件并定义一个 start
脚本:
Add the babel-cli
and babel-preset-es2015
(aka ES6) dependencies to your app's package.json file and define a start
script:
{
"dependencies": {
"babel-cli": "^6.0.0",
"babel-preset-es2015": "^6.0.0"
},
"scripts": {
"start": "babel-node --presets es2015 app.js"
}
}
然后您可以简单地执行以下命令来运行您的应用程序:
Then you can simply execute the following command to run your app:
npm start
如果您决定停止使用 Babel(例如,一旦 Node.js 支持所有 ES6 功能),您可以将其从 package.json 中删除:
If you ever decide to stop using Babel (e.g. once Node.js supports all ES6 features), you can just remove it from package.json:
{
"dependencies": {},
"scripts": {
"start": "node app.js"
}
}
这样做的一个好处是运行您的应用的命令保持不变,如果您与其他开发者合作,这会有所帮助.
One benefit of this is that the command to run your app remains the same, which helps if you are working with other developers.
这篇关于如何在启用 ES6 功能的情况下运行 Node.js 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!