JS Splitting

Sep 19, 2021·

2 min read

Play this article

Two posts ago I talked about what code splitting was and how you'd do it, and gave an example with CSS. This post I'm going to talk about how to do it in JavaScript.

You can just put all of your scripts into your HTML, but that could get unwieldy. A better way is to have one script linked to your HTML (eg index.js) then import everything else only where it's needed.

We're going to stick with our simple website that has three sections: header, main, footer and we have one JavaScript function per section, none of which depend on each other. Not at all like real life, but easy to understand the example.

You have three files, header.js, main.js and footer.js. In those files you need to export any functions in them that are run from elsewhere. Let's assume that header.js has one function inside it, which is called headerFunction.

First of all you have to export it, so other files can see it. There are two ways of exporting it, a default export or a named export.

Default export

If it's the only function in a file then the default export is easiest:

export default function headerFunction() {
  // function does something here

Although if you're using an arrow function, you can't just put export default in front of it, you have to declare it separately:

const headerFunction = () => {
  // function does something here

export default headerFunction;

Then in index.js you have:

import headerFunction from 'header';


Named export

You can only have one default export per file, so if you have multiple functions you need to export from one file, instead what you can do are named exports (either all named or you can have one that's default and the rest named). These work the same whether you have an ordinary function or an arrow function.

export function headerFunction() {
  // function does something here
export const headerFunction = () => {
  // function does something here

So the difference is no word 'default' just the word 'export'.

Then to import a named function you put curly brackets around it:

import { headerFunction } from 'header';



If you're not using a bundler, you'll get errors. After playing around with some solutions to this I found that the easiest thing to do was to install a bundler. If you've never used one before I recommend Parcel, since all you need to do is to install it and it just works.