gpt4 book ai didi

angular - 在 Angular 应用程序中使用自定义 webpack

转载 作者:行者123 更新时间:2023-12-05 07:09:04 25 4
gpt4 key购买 nike

我想在 Angular 应用程序中运行 webpack,所以我写了这样的代码。

package.json 文件

"scripts": {
"start_ar": "ng build --watch --configuration=dev_ar",
},

"devDependencies": {
"@angular-builders/custom-webpack": "^7.1.4",
"file-loader": "^1.1.11",
"html-loader": "^0.5.5",
"url-loader": "^1.0.1"
}

在angular.json文件中

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

在 webpack.config.js 中

   module.exports = {
module : {
rules: [
{
"test": /\.(jpg|png|webp|gif|otf|ani|ico|cur)$/,
"loader": "url-loader",
"options": {
"name": "[name].[hash:7].[ext]",
"limit": 10000,
"outputPath": "../assets/img/",
"publicPath": "src/assets/img/"
}
}]}};

但问题是图像仍然是原样,就像 webpack 没有运行一样,我没有错误,但我没有看到图像有任何变化,此代码中是否缺少任何内容??

最佳答案

Angular cli 不再允许您修改 webpack 文件。相反,您应该使用 Angular 构建器来执行修改

构建器之一是 ngx-build-plus .您应该查看它的文档以获得完整的功能列表

以下步骤取自它的文档

Add ngx-build-plus: ng add ngx-build-plus

Note: If you want to add it to specific sub project in your projects folder, use the --project switch to point to it: ng add ngx-build-plus --project getting-started

Remark: This step installs the package via npm and updates your angular.json so that your project uses custom builders for ng serve and ng build.

Add a file webpack.partial.js to the root of your (sub-)project:

const webpack = require('webpack');

module.exports = {
plugins: [
new webpack.DefinePlugin({
"VERSION": JSON.stringify("4711")
})
] } Use the global variable VERSION in your app.component.ts:

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

declare const VERSION: string;

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Version: ' + VERSION; } Start your application with the --extra-webpack-config switch pointing to your partial webpack config:

ng serve --extra-webpack-config webpack.partial.js -o If your project is a CLI based sub project, use the --project switch too:

ng serve --project getting-started -o --extra-webpack-config webpack.partial.js Hint: Consider creating a npm script for this command.

所以在你的情况下 webpack.partial.js 的内容将是

const webpack = require('webpack');

module.exports = {
module : {
rules: [
{
"test": /\.(jpg|png|webp|gif|otf|ani|ico|cur)$/,
"loader": "url-loader",
"options": {
"name": "[name].[hash:7].[ext]",
"limit": 10000,
"outputPath": "../assets/img/",
"publicPath": "src/assets/img/"
}
}]}};

关于angular - 在 Angular 应用程序中使用自定义 webpack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com