本文探讨一些常用的构建配置项
alias 别名:用来简化一些常用的路径
常规用法
webpack.config.js
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/'),
},
},
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
精确匹配
A trailing $ can also be added to the given object's keys to signify an exact match:
webpack.config.js
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
xyz$: path.resolve(__dirname, 'path/to/file.js'),
},
},
};
which would yield these results:
import Test1 from 'xyz'; // Exact match, so path/to/file.js is resolved and imported
import Test2 from 'xyz/file.js'; // Not an exact match, normal resolution takes place
忽略模块
Setting resolve.alias to false will tell webpack to ignore a module.
module.exports = {
//...
resolve: {
alias: {
'ignored-module': false,
'./ignored-module': false,
},
},
};
数组语法
[string] values are supported since webpack 5.
module.exports = {
//...
resolve: {
alias: {
_: [
path.resolve(__dirname, 'src/utilities/'),
path.resolve(__dirname, 'src/templates/'),
],
},
},
};