angularCLI中使用自定义webpack config

9次阅读

共计 2246 个字符,预计需要花费 6 分钟才能阅读完成。

本例子将使用在 angular 中引入 moment.js,使用 webpack 配置多语言开发环境

使用 Angular CLI 创建一个新的 Angular 应用程序:

# Install the Angular CLI globally
$ npm i @angular/cli -g

# Create a new Angular project with a name of your choosing && change directory
$ ng new AngularCustomWebpackConfig

> N
> SCSS

$ cd AngularCustomWebpackConfig

# Open this up in VS Code and Serve
$ code . && ng serve

依赖

为了使用自定义的 webpack 配置,我们需要 @angular-builders/custom-webpack 依赖项。devDependency像这样将其添加到您的项目中:

$ npm i @angular-builders/custom-webpack -D

然后,我们可以安装 moment 到我们的项目并将其导入我们的项目:

$ npm i moment --save

自定义 Webpack 配置

然后,我们可以创建一个自定义的 Webpack 配置,以剔除我们没有特别选择保留的所有语言环境。

在项目根目录中,创建一个新文件,名称 custom-webpack.config.js 如下:

const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

module.exports = {
  plugins: [
    new MomentLocalesPlugin({localesToKeep: ['fr']
    })
  ]
};

这需要我们安装moment-locales-webpack-plugin

$ npm i moment-locales-webpack-plugin -D

将此添加到 angular.json

之后,我们需要进行配置 angular.json 以使用此新配置。在 architect/build 对象内部,将 builderfrom  更新@angular-devkit/build-angular:browser@angular-builders/custom-webpack:browser并添加 customWebpackConfig 密钥:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./custom-webpack.config.js",
        "replaceDuplicatePlugins": true
      }
    }
  }
}

使用 ng 服务时的自定义 Webpack 配置

如果我们只希望最终的,内置的应用程序使用 webpack 配置,那么这就是我们需要做的所有事情。但是,如果我们想在使用时测试此配置ng serve,我们还有另一件事要做。

从以下位置安装 @angular-builders/dev-server 自定义 Web 服务器npm

$ npm i @angular-builders/dev-server -D

然后,我们可以 serve/builderangular.json文件中对其进行更新:

"serve": {"builder": "@angular-builders/custom-webpack:dev-server"}

测试

让我们检查一下它是否按预期工作!前往 app.component.ts 并将语言环境设置为fr

import {Component, OnInit} from'@angular/core';

import * as moment from 'moment'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  currentTimeFRLocale: string;

  ngOnInit(): void {moment.locale('fr');
    this.currentTimeFRLocale = moment().format('LLL');
  }
}

然后我们可以在里面显示app.component.html

大。fr正如我们特别告诉我们的那样,我们可以在语言环境中查看当前日期和时间,并将 moment 其保留在插件中。

让我们从中删除它,custom-webpack.config.js然后选择其他语言环境:

module.exports = {
  plugins: [
    new MomentLocalesPlugin({localesToKeep: ['de']
    })
  ]
};

您需要使用重新启动应用 ng serve 程序才能更新应用程序。

语言环境已从捆绑包中消失了!您还将注意到,使用这种额外的配置,捆绑包的大小要比不使用捆绑包的情况小得多。

这是没有配置的结果:

chunk {main} main.js, main.js.map (main) 22.6 kB [initial] [rendered]

这里的结果 配置:

chunk {main} main.js, main.js.map (main) 10.2 kB [initial] [rendered]
正文完
 0