简体   繁体   中英

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. I have 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?

I think you almost made it. But delete p is NOT a way to delete item from an array. you should use .splice , which can delete items from array and add items in the meantime:

    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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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