我正在尝试创建 npm 模块,但在 babeljs 官方网站上找不到单个指令。你如何使用 babel-runtime 包?从名字我猜它应该放在 package.json 的“依赖项”部分,对吧?
这里绝对没有信息:https://github.com/babel/babel/tree/master/packages/babel-runtime
在这里找到一个例子:https://strongloop.com/strongblog/javascript-babel-future/但是当我运行“babel -h”时,它没有将 --optional 列为有效参数。
最佳答案
基本原理
在转译您的代码时,Babel 实际上会注入(inject)帮助器来模拟您所针对的 ES 版本不支持的功能。
例如:class MyClass {}
利用内联帮助器 _classCallCheck
,也可以通过 require('babel-runtime/helpers/classCallCheck')
访问。
默认情况下,这些帮助程序不会在编译单元(文件)之间共享。尽管 Babel 团队将它们分解到一个地方可能会很有趣,这样可以在多次使用时节省空间。
此问题已通过创建 babel-plugin-transform-runtime
插件得到解决,该插件遍历 AST 并通过 babel-runtime的适当要求替换辅助注入(inject)
模块。这样,帮助程序在代码库中共享,避免了重复。
如何使用
假设您有一个 running Babel environment :
- 安装
babel-plugin-transform-runtime
(作为devDependency
),它会转换您的代码以删除帮助程序并使用babel-runtime
中的帮助程序。 你需要将它添加到你的 Babel 配置的plugins
数组中 - 安装
babel-runtime
(作为dependency
),这是实际的库babel-plugin-transform-runtime
假设您将在dependencies
中拥有,它将由您的转译代码在运行时使用。 您不需要在代码中的任何地方使用它。
最小片段
npm run build
将lib
文件夹编译成dist
npm start
启动dist
文件夹(依赖于babel-runtime
)
package.json
{
"scripts": {
"build": "babel lib --out-dir=dist",
"start": "node dist"
},
"dependencies": {
"babel-runtime": "^6.9.2"
},
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-plugin-transform-runtime": "^6.9.0"
},
"babel": {
"plugins": [
"transform-runtime"
]
}
}
关于node.js - 如何在 Babel 6 中使用 babel-runtime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34076117/