0

I have these local NPM packages:

           common-package
           ^          ^
           |          |
father-package       mother-package
           ^          ^
           |          |
            son-package
            

Both father-package and mother-package import common-package, and then son-package imports both father-package and mother-package

The problem here is that the son-package bundle duplicates the common-package code. The common-package has a User.ts class and as you can see there are 2 definitions of the User.ts class in the output bundle when searching for "class User {":

enter image description here

My goal is to dedupe it. I believe that is possible by tweaking webpack.config.js optimization but i cant figure how.

Here is what I have tried so far:

son-package webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    plugins:[
        new HtmlWebpackPlugin({
            template: './index.html',
            inject: true,
            filename: './index.html'
        })
    ],
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all',
                },
            },
        },
    },
    mode: 'development',
    devtool: 'source-map',
    target: 'es2017',
    entry: {
        index: './src/Index.ts'
    },
    output: {
        path: `${path.resolve('dist')}`,
        filename: '[name].js',
        library: {
            type: 'module'
        },
        chunkFormat: 'module'
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(js|jsx)$/,
                use:  'babel-loader',
                exclude: /node_modules/
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.ts'],
    }
      
};

Should i add the same optimization configuration in father-package and mother-package to webpack.config.json files?

Hope to have explained my problem well. Thanks in advance.

Btw, my node version is v18.11.0 and NPM is 8.19.2 and webpack 5.

Elkin
  • 880
  • 2
  • 12
  • 26
  • Are you sure there's duplication? Normally in this case only one copy of common-package is compiled but referenced by both. Normally there is nothing you need to do so the answer is simply do nothing. But you could have code that is not normal... – slebetman Jan 26 '23 at 10:33
  • So far in your question you have no proof that common-package is duplicated. – slebetman Jan 26 '23 at 10:34
  • @slebetman Thanks for noticing. I updated the question with a screenshot of part of the output bundle – Elkin Jan 26 '23 at 11:01

0 Answers0