先來(lái)看下效果
一般來(lái)說(shuō)
import HomePage from '../../pages/Home/HomePage'
const ScreenWidth = require('../../config.js');
修改之后
import HomePage from '~/pages/Home/HomePage'
const ScreenWidth = require('~/config.js');
組件安裝
npm 執(zhí)行
npm install babel-plugin-root-import --save-dev
yarn 執(zhí)行
yarn add babel-plugin-root-import --dev
配置文件
在項(xiàng)目根目錄下創(chuàng)建一個(gè).babelrc文件,并添加一下代碼:
{
"plugins": [
[
"babel-plugin-root-import",
{
"rootPathSuffix": "./src/",
"rootPathPrefix": "~"
}
]
]
}
/*
rootPathSuffix 是把src作為根目錄翩活,也可設(shè)置其他文件夾作為根目錄
rootPathPrefix 不設(shè)置的話(huà)默認(rèn)為 ~ 专酗, 也可自定義
*/
其他的一些用法
{
"plugins":[
"babel-plugin-root-import",
{
"paths":[
{
"rootPathPrefix": "~", // `~` 默認(rèn)
"rootPathSuffix": "./src/"
},
{
"rootPathPrefix": "@",
"rootPathSuffix": "./src/pages/Home/"
}
]
}
]
}
// 然后你就可以這樣使用插件了兽愤。
import HomePage from '~/pages/Home/HomePage';
import HomePage from '@/HomePage';