前言
相信前端开发对于 import
一定都不陌生,比如:
import test from '../../../components/test.js'
总是要写上不太优雅的冗余路径,看起来不优雅。
配置别名
我们可以用到 babel-plugin-root-import
这个插件:
npm install --dev babel-plugin-root-import
然后在配置文件 babel.config.js
中进行配置:
module.exports = {
presets: ["module:metro-react-native-babel-preset"],
plugins: [
[
"babel-plugin-root-import",
{
rootPathSuffix: "src",
},
],
],
env: {
production: {
plugins: [
[
"babel-plugin-root-import",
{
rootPathSuffix: "src",
},
],
],
},
},
};
通过 rootPathSuffix
来匹配给需要的路径起别名,默认别名是 ~
。
如果另有需要,可以用 rootPathPrefix
来自行修改,比如想用 @root
来替代 src
根目录,如下:
...
{
rootPathPrefix: "@root",
rootPathSuffix: "src",
},
...
然后!!!切记要执行如下命令,清除下 watchman
和 npm
的缓存:
watchman watch-del-all
npm start -- --reset-cache
然后,本文开头的引用就可以改为:
// import test from '../../../components/test.js'
import test from '~/components/test.js'
看起来是不是优雅多了?
让编辑器能自动跳转
配置了别名,你会发现点击,无法跳转到指定文件。
别担心,在根目录增加一个 jsconfig.json
文件,对于你起别名的目录,在 paths
里面进行配置即可:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["src/*"]
},
"target": "ES6",
"module": "commonjs",
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
然后,对于 VSCode
,就可以直接使用了。 Webstorm
需要做下配置:
【Preferences】 => 【Language & Frameworks】 => 【Webpack】中,选择刚才创建的 jsconfig.json
文件即可。
然后,我们就可以优雅的开发了~