本例子将使用在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
对象内部,将builder
from 更新@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/builder
在angular.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]
发表回复