Babel What is it? ?
Babel It's a JavaScript compiler
Babel It's a tool chain , It's mainly used to use ECMAScript 2015+ Syntax written code into backward compatible JavaScript grammar , To be able to run in current and older browsers or other environments . Listed below are Babel What I can do for you :
- Grammar conversion
- adopt Polyfill Way to add missing features to the target environment ( Through a third party polyfill modular , for example core-js, Realization )
- Source code conversion (codemods)
node Environment use
The whole configuration process includes :
1、 Run the following command to install the required package (package):
npm install --save-dev @babel/core @babel/cli @babel/preset-env
Copy code
2、 Create a project named... At the root of the project babel.config.json
Configuration file for ( need v7.8.0
Or later ), And copy the following into this file :
{ "presets": [ [ "@babel/env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1" }, "useBuiltIns": "usage", "corejs": "3.6.5" } ] ] }
Copy code
If you're using Babel The old version of , Then the file name is babel.config.js
.
const presets = [ [ "@babel/env", { targets: { edge: "17", firefox: "60", chrome: "67", safari: "11.1", }, useBuiltIns: "usage", corejs: "3.6.4", }, ], ]; module.exports = { presets };
Copy code
3、 Running this command will src
All the code in the directory is compiled to lib
Catalog :
./node_modules/.bin/babel src --out-dir lib
Copy code
4、 Core library
npm install --save-dev @babel/core @babel/cli
Copy code
5、 Manual switching
./node_modules/.bin/babel src --out-dir lib
Copy code
This will resolve src
All under directory JavaScript file , And apply the code conversion function we specified , Then output each file to lib
Under the table of contents . Since we haven't specified any transcoding functions yet , So the output code will be the same as the input code ( Do not keep the original code format ). We can pass the transcoding function we need as a parameter .
In the above example, we used --out-dir
Parameters . You can go through --help
Parameter to see a list of all parameters that the command-line tool can accept . But the most important thing for us now is --plugins
and --presets
These two parameters .