问题
In order to do runtime transformations in Babel you need to require and use babel-core/register. I have no idea what register means in this sense, i.e. the actual definition.
The page isn't very helpful.
What does this actually mean?
回答1:
ok, so the purpose of babel as you know is to transpile your js current code to an understandable version of js for the given environment, tool, framework you're using. Those vary as listed here, How to use Babel with your tool of choice. In the node environment, babel does not exist as part of its core APIs, so it needs to be added as an npm package first, (my example is for @babel 7.x ). And because babel is separated to accommodate different tools, we need to add @babel/core for the core functionality and @babel/preset-env which enables transforms for ES2015+.
npm install @babel/core @babel/preset-env --save-dev
or
npm i -D @babel/core @babel-preset
now as we use babel we want the tell it about the available preset by setting up a .bablerc file in the root directory, more on that found here
{
"presets": ["@babel/preset-env"]
}
now to get to the register aspect. Because of the nature of ES6 modules as explained here, if we want to run babel without a build step like webpack or rollup, and run babel 'on the fly' we need to register babel into nodes runtime The require hook will bind itself to node’s require and automatically compile files on the fly. This is equivalent to CoffeeScript’s coffee-script/register. reference from babel usage docs for babel-register found here. Therefore along with the previous npm install we add @babel/register:
npm install @babel/register --save-dev
or
npm i -D @babel/register
Last of all, either require it in the application files (generally, in the index.js file that is the entry point in your app and contains requires to other files) or add it in the cli.
// in .js file
require("@babel/register");
or
// in command line, don't add it to the .js file but instead use the -r flag for require
npx -r @babel/register index.js
(more on npx can be found here)
As a note the .bablerc, it can be skipped and a "babel" property with a and options object can be place in the package.json file, ex
//package.json in root
"babel": {
"presets":[
"@babel/preset-env"
]
}
a great example in babel 6 can be found by a great teacher's github, Josh Miller, here Hope this helps for an understanding of 'register' needs.
来源:https://stackoverflow.com/questions/35349936/what-does-register-mean-in-babel-register