简体   繁体   中英

What does webpack code splitting mean and how does it work?

Correct me if I'm wrong, but what webpack does is bundle up all your files into one and then serves them to the client to reduce requests. Afterwards, the client still has to load that file for your app to work, so in order to make it faster, code splitting lets the client loads up different parts of your app on demand, correct?

I'm not sure how to do that with the below code from the docs. So if I put the below code in a file that has already been loaded, the first parameter refer to the dependencies and the 2nd refer to the callback. That means anything I want to do with the dependencies have to go in the callback, correct?

require.ensure(["module-a", "module-b"], function() {
  var a = require("module-a");
  // ...
});

Code splitting is one of the most compelling features of webpack. It allows you to split your code into various bundles which you can then load on demand for example when a user navigates to a matching route, or on an event from the user. This allows for smaller bundles, and allows you to control resource load prioritization

Split app and vendor code var webpack = require("webpack");

module.exports = {
  entry: {
    app: "./app.js",
    vendor: ["jquery", "underscore", ...],
  },
  output: {
    filename: "bundle.js"
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js")
  ]
};

This will remove all modules in the vendor chunk from the app chunk. The bundle.js will now contain just your app code, without any of its dependencies. These are in vendor.bundle.js.

In your HTML page load vendor.bundle.js before bundle.js.

<script src="vendor.bundle.js"></script>
<script src="bundle.js"></script>

More Info

React code splitting

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