简体   繁体   English

React webpack 配置:是否可以只为数组中的一个插件替换配置,而不重置插件数组?

[英]React webpack config: is it possible to replace config for only one plugin in array, without reset an array of plugins?

I'm using react-app-rewired plugin for build.我正在使用 react-app-rewired 插件进行构建。 I have config-overrides.js:我有 config-overrides.js:

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = function override(config, env) {
    if( !config.plugins ) {
        config.plugins = [];
    }

    const miniCssOptions = {
        filename: "[name].[hash].css"
    }
    let miniCssAdded = false;

    if( config.plugins.length ) {
        config.plugins.forEach( p => {
            if( p instanceof MiniCssExtractPlugin) {
                delete p;
                p = new MiniCssExtractPlugin( miniCssOptions );
                miniCssAdded = true;
            }              
        })
    }

    if( !miniCssAdded ) {
        config.plugins.push( new MiniCssExtractPlugin( miniCssOptions ) );
    }
    
    config.plugins.push( new CleanWebpackPlugin() );

    config.plugins.push( new HtmlWebpackPlugin({
        title: 'Caching',
    }) );
    

    config.output.filename ='static/js/[name].[hash].js';
    config.output.chunkFilename ='static/js/[name].[hash].js';
    config.output.path = path.resolve(__dirname, 'build');
    
    config.optimization.splitChunks= {
        cacheGroups: {
            vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                chunks: 'all',
            }
        }
    }      

    return config;
}

But it doesn't work.但它不起作用。 I have the following results:我有以下结果: 哈希没有改变

Can I replace options only for specific plugin without reseting all plugins created by react-app?我可以只替换特定插件的选项而不重置 react-app 创建的所有插件吗?

I think you almost made it.我想你几乎做到了。 But delete p is NOT a way to delete item from an array.但是delete p不是从数组中删除项目的方法。 you should use .splice , which can delete items from array and add items in the meantime:您应该使用.splice ,它可以从数组中删除项目并同时添加项目:

    config.plugins.forEach( (p,i) => {
        if( p instanceof MiniCssExtractPlugin) {
            //delete p;
            config.plugins.splice(i,1, new MiniCssExtractPlugin( miniCssOptions ));
        }              
    })

The accepted answer with instanceof did not work for me, when i tried to replace webpack-livereload-plugin , this did: instanceof 接受的答案对我不起作用,当我尝试替换webpack-livereload-plugin ,这样做了:

config.plugins.forEach((p, i) => {
    if(p.constructor.name === 'LiveReloadPlugin') {
        config.plugins.splice(i, 1, new LiveReloadPlugin({
            port: 35729
        }));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM