Code Splitting
Code Splitting
Parcel supports zero-configuration code splitting out of the box. This allows you to split your application code into independent bundles that can be loaded on demand, meaning smaller initial bundle sizes and faster load times. When a user browses a module in the application and needs to load it, Parcel automatically takes care of loading sub-packages on demand.
Code splitting is controlled through syntax proposals using the dynamic import() function, which works like a normal import statement or require function, but returns a Promise. This means that modules are loaded asynchronously.
The following example shows how to use dynamic imports to load subpages of an application on demand.
// pages/about.js export function render() { // 渲染页面 } import('./pages/about').then(function (page) { // 渲染页面 page.render(); });
Since import() returns a Promise, you can also use async/await syntax. You may need to configure Babel to transport the syntax until browsers have wider support.
const page = await import('./pages/about'); // 渲染页面 page.default();
Dynamic imports are also lazy loaded in Parcel, so you can still put all your import() calls at the top of the file, and they won't be loaded until the subpackage is used . The following example shows how to dynamically lazy load subpages of an application.
// 设置页面名称到动态导入映射。 // 这些页面都不会被加载,直到使用前。 const pages = { about: import('./pages/about'), blog: import('./pages/blog') }; async function renderPage(name) { // 延迟加载请求页面。 const page = await pages[name]; return page.default(); }
Note: If you want to use async/await in a browser that does not natively support it, please remember to introduce babel-polyfill in your application or introduce babel-runtime in the library
babel-plugin-transform-runtime 。 yarn add babel-polyfill import "babel-polyfill"; import "./app";
Please read the documentation of babel-polyfill and babel-runtime.