babel-plugin-root-import 一个可以让你基于根路径导入组件的 Babel 插件(支持 import、require)
痛点
// 不使用这个插件...
import SomeExample from '../../../some/example.js'
const OtherExample = require('../../../other/example.js')
// 使用 babel-plugin-root-import 你可以这么写...
import SomeExample from '~/some/example.js'
const OtherExample = require('~/other/example.js')
安装
$ yarn add -D babel-plugin-root-import eslint-import-resolver-babel-plugin-root-import
配置文件
babel.config.js:
module.exports = {
...
plugins: [
[
'babel-plugin-root-import',
{
rootPathSuffix: 'src',
rootPathPrefix: '~',
},
],
],
...
}
.eslintrc.js
{
settings: {
'import/resolver': {
'babel-plugin-root-import': {
rootPathSuffix: 'src',
rootPathPrefix: '~',
},
},
},
}
tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["src/*"]
}
}
}