在Angular中自定义Webpack配置

本文章只针对Angular CLI 8版本

1.安装angular-builders

cnpm i @angular-builders/custom-webpack -D
cnpm i @angular-devkit/build-angular -D

2.更改angular.json配置 

"projects": {
  ...
  "[your-porject]": {
    ...
    "architect": {
      ...
      "[architect-target]": {
        "builder": "@angular-builders/custom-webpack:[browser|server|karma|dev-server]"
        "options": {
          "customWebpackConfig":{
             "path":'./webpack.config.js',
             "mergeStrategies": {
                "externals": "replace",
                "module.rules": "prepend"
             }
           },
          "indexTransform": "./index-html-transform.js",
          ...
        }    

解释一下:
[architect-target]:类似项目中的"build"或者"serve"(也就是ng build/serve)命令,
builder:angular.json:默认的配置是@angular-devkit/build-angular:browser,这个是angular内部的配置,
换成@angular-builders/custom-webpack就可以使用自定义的配置,配置只接受browser|server|karma|dev-server这四个选项
customWebpackConfig.path:自定义的webpack的路径
customWebpackConfig.mergeStrategies:webpack配置合并方式,只能是append|prepend|replace。默认为append
     append:将自定义配置的字段添加到的默认配置项中
     prepend:字面意思,将自定义配置的字段添加到默认配置加载程序数组的最前面。
     
replace:自定义的配置完全替换默认配置,使用自定义的配置
indexTransform:index-html-transform.js是用来更改dist目录下index.html文件里面的内容

举个例子:

//   angular.json
 ...
    "architect": {
        ...
        "build": {
            "builder": "@angular-builders/custom-webpack:browser",
            "options": {
                "customWebpackConfig": {
                    "path": "./webpack-prod.config.js"
                },
               "indexTransform": "./index-html-transform.js"
            }
        },
        "serve": {
            "builder": "@angular-builders/custom-webpack:dev-server",
            "options": {
                "customWebpackConfig": {
                    "path": "./webpack-dev.config.js"
                }
            }
        },
       ...
    }

此时如果我们想要ng build的时候复制静态资源,或者抽离出某个js库,就可以这么干

// webpack-prod.config.js

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (config, options) => {
  config.plugins.push(
    new CopyPlugin([
      { from: path.join(__dirname, "src/utils"), to: path.join(__dirname, "dist/utils") }
    ])
  );
  if(!config.optimization.splitChunks.cacheGroups.moment){
    config.optimization.splitChunks.cacheGroups.moment = {
      name:'momentFile/moment', // 打包到dist/momentFile/moment
      chunks: 'all',
      test: /moment\.js/,
      enforce: true
    }
  }

  return config;
};

打包后的目录

更改index.html内容

// index-html-transform.js

module.exports = (targetOptions, indexHtml) => {
    const i = indexHtml.indexOf('</body>');
    const config = `<script src="momentFile/moment.js" type="module"></script>`;
    return `${indexHtml.slice(0, i)}
              ${config}
              ${indexHtml.slice(i)}`;
  };

打包后的index.html页面

具体使用可以参考这里

发布了112 篇原创文章 · 获赞 149 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/l284969634/article/details/103233903
今日推荐