angularCLI中使用自定义webpack config

本例子将使用在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]

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理