Is it okay to use babel-node in production
我一直在使用babel-node和带有babelify转换的browserify开发站点,以支持ES6语法。
我只是想知道,我可以在生产环境中以
这是我正在运行用于构建和开始开发的命令
1 2 3 4 5 | // npm run build browserify -t [babelify] client.js > public/js/bundle.js", // npm start babel-node server.js" |
这是我的开发依赖
1 2 3 | "babel":"^4.0.1", "babelify":"^5.0.3", "browserify":"^8.0.3" |
对于客户端代码,您正在做正确的事情。
对于服务器端代码,我只需要使用babel-cli进行常规构建
According to http://babeljs.io/docs/setup/#babel_register,
babel-register is not meant for production use The require hook is primarily recommended for simple cases.
适用于Babel 6+
从Babel 6开始,默认情况下不包含任何转换。因此,让我们从安装
1 | $ npm install --save-dev babel-cli babel-preset-es2015 |
在您的
1 2 3 | { "presets": ["es2015"] } |
将
1 2 3 | "scripts": { "build":"babel src -d build" } |
然后建立它!
1 | $ npm run build |
然后运行您的代码。此时,您将要执行
1 | $ npm start |
对于Babel <= 5,只需使用require钩子即可。
1 | require("babel/register"); |
All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel. The polyfill is also automatically required.
您将能够将源文件保留在ES6中,但仍可以使用
根据您的评论,您似乎遇到了一些麻烦。请特别注意上面黄色突出显示的部分。您的第一个文件只能是ES5,它由节点本身运行。随后的所有需求将由Babel进行转换...
这是典型设置的样子
server.js
1 2 3 4 5 6 7 | // only ES5 is allowed in this file require("babel/register"); // other babel configuration, if necessary // load your app var app = require("./app.js"); |
app.js
1 2 | // this file will be loaded through babel // you can now use ES6 here and in every other include |
燃烧起来;动起来!
1 | $ node server.js |
我刚刚写了一篇关于这个话题的博客文章
Babeljs CLI文档警告以下内容:
babel-node not meant for production use
You should not be using babel-node in production. It is unnecessarily
heavy, with high memory usage due to the cache being stored in memory.
You will also always experience a startup performance penalty as the
entire app needs to be compiled on the fly.
这是一个示例,说明如何设置npm脚本以使用node(而不是babel-node)运行应用程序。
1 2 3 4 5 6 7 8 9 10 11 | "scripts": { "clean":"rm -rf build && mkdir build", "build-css":"node-sass scss/app.scss public/css/app.css", "build-server":"babel -d ./build ./server -s", "build":"npm run clean && npm run build-css && npm run build-server", "lint":"eslint source/ --quiet", "start":"node ./build/index.js", "debug":"node --debug ./build/index.js", "test":"for i in $(ls tests/); do babel-node \"./tests/${i}\" | faucet ; done", "validate":"npm run lint; npm run test && npm outdated --depth 0" }, |
您可以在博客文章中找到更多详细信息
权衡在生产中使用babel-node的利弊很重要。
-
babel-node 确实在商品硬件上增加了半秒到一秒的启动成本。但是,如果您的应用程序是运行时间较长的服务器,则启动成本并不重要。 - 尝试测量额外的内存消耗。以我的应用程序为例(读取和处理时间序列数据),只有20MB。根据您的情况,这可能并不重要。
另一方面,
-
使用babel-node直接简化开发-您将不需要" build"脚本,也将没有单独的
src /lib 和dist 目录 -
如果您是从本地文件
import 导入的,您是从src/myutils 导入还是从lib/myutils 导入?使用babel-node 消除了该问题。
我仅将Babel用于模块支持。现在,V8刚刚在2017年1月10日发布了对模块的支持。希望我们能在几个月后看到Node支持模块的情况,这使我有理由使用Babel。
@cuadraman的答案比@naomik更准确。
要简短地回答您的问题:不,您不应该明确调用
官方教程提供了在节点(而不是浏览器端!)上启动并运行所需的一切:https://github.com/babel/example-node-server。阅读!我发现了很多使用各种方法引起误导的博客教程,并且发现本文最容易理解。
奖励:与许多人的想法相反,所有的转换魔术都可以在本地安装(使用