-
Node
sudo npm install @babel/core @babel/cli @babel/preset-env
-
Working with webpack
npm init sudo npm install webpack sudo npm install --save-dev babel-loader
NOTE: it's not a good idea to install Babel globally, that would make your project dependent on a specific system env;
Make sure the charset="utf-8"
attribute is included
<script
src="https://unpkg.com/[email protected]/browser.min.js"
charset="utf-8"
></script>
See Config Files - Babel for details.
The recommended way for configs, should be in the root of a project.
module.exports = function (api) {
api.cache(true);
const presets = [ ... ];
const plugins = [ ... ];
return {
presets,
plugins
};
}
The old method for configs, put the following in .babelrc
to use the latest Babel features.
{
"presets": ["env"]
}
package.json
babel.config.js
packages/
mod1/
package.json
.babelrc.json
index.js
babel.config.js
is for repo-wide configs;.babelrc.json
is for configs specific tomod1
;- In
mod1
, if you want to compileindex.js
, you need to setrootMode
option to beupward
:-
CLI
babel --root-mode upward src -d lib
-
Webpack
module: { rules: [{ loader: "babel-loader", options: { rootMode: "upward", } }] }
-
Presets are just pre-defined collections of plugins, you can define your own presets:
module.exports = function() {
return {
plugins: ['pluginA', 'pluginB', 'pluginC']
};
};
then use it like this:
{
"presets": ["./myProject/myPreset"]
}
https://babeljs.io/docs/en/plugins#plugin-ordering
- Plugins run before Presets.
- Plugin ordering is first to last.
- Preset ordering is reversed (last to first).
-
compile for browser
babel script.js --watch --out-file script-compiled.js
-
run node js script
babel-node node-script.js
-
or use webpack
webpack --watch
in VSCode launch.json
...
// babel-node debugging demo
{
"type": "node",
"request": "launch",
"name": "Babel Node",
"program": "${file}",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node",
"args": []
},
// babel-node attaching demo
{
"type": "node",
"request": "attach",
"name": "Babel Node Attaching",
"port": 9229,
"timeout": 120000,
"localRoot": "${workspaceFolder}/",
},
...
for attaching mode, launch the script like this:
babel-node --inspect=9229 app.js