Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include only used imports in the packaged bundle ReactJS

I wanna use only one component from Material Ui library . I know i can import only one component using ES6 import but does webpack treeshake and remove other components from the library or include them in production .

Please help me.

like image 559
Ruhul Amin Avatar asked Jan 27 '26 04:01

Ruhul Amin


1 Answers

Webpack from v2 onwards eliminates unused exports in two steps:

First, all ES6 module files are combined into a single bundle file in which exports that were not imported anywhere are not exported, anymore.

Second, the bundle is minified, while eliminating dead code. Therefore, entities that are neither exported nor used inside their modules do not appear in the minified bundle. Without the first step, dead code elimination would never remove exports.

Unused exports can only be reliably detected at build time if the module system has a static structure.

Webpack doesn't perform tree-shaking by itself. It relies on third party tools like UglifyJS to perform actual dead code elimination.

To do that, you would install it using

npm install --save-dev uglifyjs-webpack-plugin

And then adding it into the config:

webpack.config.js

const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new UglifyJSPlugin()
  ]
};

So when you add this config, your unused exports are not longer present in the minified build.

like image 168
Shubham Khatri Avatar answered Jan 28 '26 20:01

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!