demand
Project technology stack: webpack + typescript + eslint
code uses relative paths to import modules multiple times, which looks complicated and unsightly, as follows:
import fetch from '../../../../utils/fetch';
How to optimize the above code?
import fetch from 'utils/fetch';
Program
step1: Configure webpack's resolve.alias
module.exports = {
entry: {
main:'./main.js',
},
output: {
path:__dirname+'/dist',
filename: '[name].js'
},
resolve:{
//配置别名,在项目中可缩减引用路径
alias: {
'utils': resolve('app/utils'),
'assets': resolve('app/assets')
}
},
plugins: []
};
step2: Configure tsconfig.json
{
compilerOptions: {
"baseUrl": ".",
"paths": {
"utils/*": ["app/utils/*"],
"assets/*": ["app/assets/*"],
}
}
}
ESLint reports import/no-unresolved error
Solution:
- Online recommendation [not tried]
- Brute force solution: restart vscode【It's ok, let's talk about it if you encounter it again】