要在Babel中从外部文件夹导入模块,你需要使用Babel的插件babel-plugin-module-resolver
。下面是一个包含代码示例的解决方法:
babel-plugin-module-resolver
插件:npm install --save-dev babel-plugin-module-resolver
.babelrc
文件,并添加以下内容:{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"@components": "./src/components",
"@utils": "./src/utils",
// 添加你的其他模块别名
}
}]
]
}
这将配置Babel使用babel-plugin-module-resolver
插件,并定义模块的别名。
./src/components/Button.js
的组件,你可以这样导入它:import Button from '@components/Button';
这将使Babel从./src/components/Button.js
文件中导入Button
组件。
注意:在你的IDE或编辑器中,你可能需要安装插件来支持别名路径的解析,例如VSCode的Babel JavaScript
插件。
希望这个解决方法能帮助到你!