简体   繁体   中英

Is there any way to avoid loading npm packages on pageload of React application

I am using few big sized npm packages (slate.js) in my project. The problem is, slate (and other npm packages) is automatically loaded on page load, even its only used inside a lazy-loaded component.

I am trying to avoid loading on pageload slate and few other packages.

So far, I used sideEffects and usedExports in my webpack configuration, but I couldnt accomplish anything useful. Webpack still automatically puts slate and other npm packages automatically in vendor.js as well as injecting it to published html file (by using HtmlWebpackPlugin I believe)

(fyi, I am using CRA along with config-overrides for webpack)

I don't think this code useful, but here is my webpack optimization property.

config.optimization = {
      usedExports: true,
      splitChunks: {
        chunks: "async",
        maxSize: 750000,
        cacheGroups: {
          react: {
            test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
            name: "react",
            chunks: "all",
          },
          slate: {
            test: /[\\/]node_modules[\\/](slate|slate-react)[\\/]/,
            name: "slate",
            chunks: "all",
          },
        },
      },
    };

You'll also need to import the packages using dynamic import() s :

// likely bundles slate up into your main vendor bundle :(
import slate from 'slate';
// slate will likely get its own webpack chunk, yay!
export default async function doSomethingWithSlate() {
  const slate = await import('slate');
  // do things with slate
}

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