I'm trying to setup Babel 7. Never used Babel before, so i'm really starting from scratch. I've managed to install and use @babel/plugin-proposal-optional-chaining
, but I'm struggling with babel-plugin-root-import
.
Here is my package.json
//package.json
"scripts": {
"start": "nodemon src/index.js --exec babel-node"
},
"devDependencies": {
"@babel/cli": "^7.0.0-beta.51",
"@babel/core": "^7.0.0-beta.51",
"@babel/node": "^7.0.0-beta.51",
"@babel/preset-env": "^7.0.0-beta.51"
},
"dependencies": {
"@babel/plugin-proposal-optional-chaining": "^7.0.0-beta.51",
"@babel/polyfill": "^7.0.0-beta.51",
"babel-plugin-root-import": "^6.1.0"
}
//babel.config.js
module.exports = {
"presets": ["@babel/preset-env"],
"plugins": [
["@babel/plugin-proposal-optional-chaining"],
["babel-plugin-root-import",{
"rootPathPrefix": "@"
}]
]
};
Below is my code:
//src/index.js
require("./foo/index.js")();
//src/foo/index.js
module.exports = function() {
console.log("Foo loaded")
}
When I execute the code above, I get Foo loaded
in my console.
When I change src/index.js with the following:
//src/index.js
require("@/foo/index.js")();
I get the following error:
internal/modules/cjs/loader.js:596
throw err;
^
Error: Cannot find module '../foo/index.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
at Function.Module._load (internal/modules/cjs/loader.js:520:25)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Node.js\dev\babel7\src/index.js:2:1)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Module._compile (C:\Node.js\dev\babel7\node_modules\pirates\lib\index.js:91:24)
at Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Object.newLoader [as .js] (C:\Node.js\dev\babel7\node_modules\pirates\lib\index.js:96:7)
at Module.load (internal/modules/cjs/loader.js:612:32)
[nodemon] app crashed - waiting for file changes before starting...
If I don't set the rootPathPrefix in babel.config.js, I also cannot use the plugin with paths starting with ~, which is supposed to be the default value. What is wrong?
Many thanks!
If you run babel-cli directly with npx babel src/index.js
just to check the output, you will find that the root import plugin is correctly changing:
require("@/foo/index.js")();
into:
require("../foo/index.js")();
@
(the project root) is correctly replaced in the index.js
file inside the src folder with ..
If you want @
to refer to root/src
you can set the "rootPathSuffix": "src"
option. Without that option you would have to do:
require("@/src/foo/index.js")();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.