Angular 如何修改webpack配置(配置loader)
1. 修改Angular CLI webpack 配置
1.1 安装 @angular-builders/custom-webpack
npm install -D @angular-builders/custom-webpack
1.2 新建webpack配置文件extra-webpack.config.js
并写入配置信息
module.exports = {
// webpack config
};
1.3 修改angular.json
"architect": {
"build": {
- "builder": "@angular-devkit/build-angular:browser",
+ "builder": "@angular-builders/custom-webpack:browser", // <=
+ "options": {
+ "customWebpackConfig": { // <=
+ "path": "./extra-webpack.config.js", // <=
+ "mergeRules": { // <=
+ "externals": "replace" // <=
+ } // <=
},
// ....
"serve": {
- "builder": "@angular-devkit/build-angular:dev-server",
+ "builder": "@angular-builders/custom-webpack:dev-server",
"options": {
+ "browserTarget": "你的项目名:build",
// ...
}
}
1.4 重启项目
2. angular 中使用 require.context
和配置 loader
2.1 安装@types/webpack-env
npm i -D @types/webpack-env
2.2 修改tsconfig.app.json
"compilerOptions": {
"outDir": "./out-tsc/app",
+ "typeRoots": ["node_modules/@types", "./types"],
"types": [
+ "webpack-env"
]
},
2.3 配置相应loader
(file-loader
为例)
npm i -D file-loader
// extra-webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.svg$/,
use: ['file-loader']
}
]
}
};
2.4 usage
const file = require.context('src/assets/image/pc/', false, /\.svg$/);
// ...
为之则易,不为则难。