Reputation: 325
I'm trying to create npm module and I can't find single instruction on official babeljs website. How do you use babel-runtime package? From name I'm guessing it should be placed in "dependencies" section of package.json, right?
Absolutely no information here: https://github.com/babel/babel/tree/master/packages/babel-runtime
Found one example here: https://strongloop.com/strongblog/javascript-babel-future/ but when I run "babel -h" it doesn't list --optional as a valid parameter.
Upvotes: 27
Views: 23630
Reputation: 7342
When transpiling your code, Babel will actually inject helpers to emulate features not supported by the ES version you target.
For example: class MyClass {}
leverages the inline helper _classCallCheck
, which can also be accessed through require('babel-runtime/helpers/classCallCheck')
.
By default, those helpers are not shared between the compilation units (the files). The Babel team though it might be interesting to factorize them in one place, allowing to save space when they are used multiple times.
This issue has been addressed by creating the babel-plugin-transform-runtime
plugin, which walks the AST and replaces the helpers injections by the appropriate requires of the babel-runtime
module. That way the helpers are shared across the codebase and the duplication is avoided.
Assuming you have a running Babel environment:
babel-plugin-transform-runtime
(as a devDependency
), which transforms your code to remove the helpers and uses the ones in babel-runtime
. You need to add it to the plugins
array of your Babel configurationbabel-runtime
(as a dependency
), which is the actual library babel-plugin-transform-runtime
assumes you are going to have in your dependencies
, it will be used by your transpiled code at runtime. You do not need to require it anywhere in your code.npm run build
compiles the lib
folder into dist
npm start
starts the dist
folder (which depends on 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"
]
}
}
Upvotes: 45
Reputation: 161607
The runtime is optional, but like everything else in Babel 6, it is primarily enabled by adding a plugin. In this case, you need http://babeljs.io/docs/plugins/transform-runtime/
plugins: ["transform-runtime"]
babel-runtime
is a package that contains a polyfill and many other things that Babel can reference. You'd install it in your app with npm install babel-runtime
transform-runtime
is a Babel plugin to process your source code and inject import foo from "babel-runtime"
statements so that babel-runtime
is actually used. You'd also install this with npm install babel-plugin-transform-runtime
.Upvotes: 9