Note: This page covers Parcel 1, the documentation for Parcel 2 is being worked on here: v2.parceljs.org

✂️ Code Splitting

Parcel supports zero configuration code splitting out of the box. This allows you to split your application code into separate bundles which can be loaded on demand, which means smaller initial bundle sizes and faster load times. As the user navigates around in your application and modules are required, Parcel automatically takes care of loading child bundles on demand.

Code splitting is controlled by use of the dynamic import() function syntax proposal, which works like the normal import statement or require function, but returns a Promise. This means that the module is loaded asynchronously.

Using dynamic imports

The following example shows how you might use dynamic imports to load a sub-page of your application on demand.

// pages/about.js
export function render() {
  // Render the page
}
import('./pages/about').then(function(page) {
  // Render page
  page.render()
})

Dynamic imports with async/await

Because import() returns a Promise, you can also use async/await syntax. You probably need to configure Babel to transpile the syntax though, until it is more widely supported by browsers.

const page = await import('./pages/about')
// Render page
page.render()

Dynamic imports are also lazily loaded in Parcel, so you can still put all your import() calls at the top of your file and the child bundles won't be loaded until they are used. The following example shows how you might lazily load sub-pages of an application dynamically.

// Setup a map of page names to dynamic imports.
// These are not loaded until they are used.
const pages = {
  about: import('./pages/about'),
  blog: import('./pages/blog')
}

async function renderPage(name) {
  // Lazily load the requested page.
  const page = await pages[name]
  return page.render()
}

Note: If you would like to use async/await in browsers that don't support it natively, remember to include babel-polyfill in your app or babel-runtime + babel-plugin-transform-runtime in libraries.

yarn add babel-polyfill
import 'babel-polyfill'
import './app'

Read the docs on babel-polyfill and babel-runtime.

Bundle resolution

Parcel infers the location of bundles automatically. This is done in the bundle-url module, and uses the stack trace to determine the path where the initial bundle was loaded.

This means you don't need to configure where bundles should be loaded from, but also means you must serve the bundles from the same location.

Parcel currently resolves bundles at the following protocols: http, https, file, ftp, chrome-extension and moz-extension.

Help us improve the docs

If something is missing or not entirely clear, please file an issue on the website repository or edit this page.