Home > OS >  Why isn't webpack tree-shaking swiperjs modules?
Why isn't webpack tree-shaking swiperjs modules?

Time:02-12

So, swiperjs, from docs:

"By default Swiper exports only core version without additional modules (like Navigation, Pagination, etc.). So you need to import and configure them too:"

  // core version   navigation, pagination modules:
  import Swiper, { Navigation, Pagination } from 'swiper';

Well, I did. This is my index.js test file:

import Swiper, { Navigation, Pagination } from 'swiper';
console.log(Swiper);

And this is my webpack config:

const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  //mode: 'development',
  mode: 'production',
  watch: true,
  entry: {
    index: './src/index.js',

  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  optimization: {
    minimize: true,
    usedExports: true,
  }

  plugins: [
    new BundleAnalyzerPlugin()
  ],

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/preset-env'] }
        }
      } // babel
    ] // rules
  } // module
};

Well, the BundleAnalyzer graph shows that ALL the swiper modules are bundled. Why? How can I avoid that? I already disabled sideEffect from package.json and activated providedExports in optimizations.

The source code of swiper.esm.js is copied here for reference: https://jsfiddle.net/fw4zj8qk/

CodePudding user response:

I've found out the issue: with swiper (at least), sideEffects option must be used at loader level and not at package level. Or maybe you can use at package level, but explicitly declaring the files. Didn't try though. Instead, it did worked by setting sideEffects like this:

  module: {
    rules: [
      // [...] here normally there are babel settings and the like
      
      { // here doing the swiper loader and declaring no sideEffects
        test: /swiper\.esm\.js/,
        sideEffects: false
      }
    ] // rules
  } // module

Now swiper gets tree shaked.

  • Related