在项目中咱们会使用一些公共的组件或者方法,可是若是项目层级比较深而且组件比较多的话,写起来就比较麻烦.css
client
├── components
│ └── layout
│ │ └── index.jsx
│ │ └── inex.scss
│ └── header
│ └──index.jsx
│ └──index.scss
│
├── utils
├── constants
├── pages
| └── 2019
│ └── dome
| ├── container
| └──home
| └──index.jsx
| └──index.scss
|-
复制代码
好比我在配置resolve.alias以前我须要在home组件中引用components
下了的header组件我须要这样写webpack
import header from '../../../../components/header';
复制代码
感受写起来好痛苦啊,而且若是你想要将某个文件移动到不一样的文件夹时,手动更改路径就会更加痛苦。web
咱们在webpack.config.js
中npm
resolve: {
extensions: [
'.jsx', '.js',
'.web.ts', '.web.tsx', '.web.js', '.web.jsx',
'.ts', '.tsx',
'.json',
],
alias: {
// 添加目录便于引用
'@components': path.resolve(__dirname, '../components'),
'@utils': path.resolve(__dirname, '../utils'),
},
},
复制代码
咱们就能够这样引用了,你根本不用担忧路径的问题。json
import Layout from '@components/layout'
复制代码
可是光这样仍是不行,若是你的项目中引入eslint代码检测,eslint就会报路径错误,这个时候就须要安装一个插件:bash
npm install eslint-plugin-import eslint-import-resolver-alias --save-dev
复制代码
而后在你的.eslintrc.js中增长以下代码:dom
"settings": {
"import/resolver": {
"alias": {
"map": [
["@components", path.resolve(__dirname, './components')],
["@utils", path.resolve(__dirname, './utils')]
]
}
}
}
复制代码
如今eslint 不报错了,可是在VScode
中使用ctrl+
鼠标左键没法识别别名路径,这就给咱们调试代码代码了麻烦。编辑器
接下来咱们就要新建一个文件jsconfig.json
让编辑器能识别到咱们的别名.ui
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@utils/*":["utils/*"]
}
}
}
复制代码
参考连接:spa