Skip to content

Use ECMAScript Modules instead of CommonJS #4515

@jkjustjoshing

Description

@jkjustjoshing

ECMAScript Modules (aka "ES6 Modules" or "ESM") is a module system that natively works in most browsers. Newer versions of Node.js also natively support it. The USWDS javascript code should switch from the current module system, CommonJS, to using ECMAScript Modules.

What makes ESM better?

  • Tools like Rollup and Webpack can tree-shake ESM dependencies, but can't tree-shake CommonJS dependencies. If we want to do the following:
    import { accordion } from 'uswds/src/js/components'
    import domready from 'domready'
    domready(() => {
        accordion.on()
    })
    Webpack or Rollup knows that we only need the accordion component's javascript, and it can delete all other component javascript.
    Caveat: tree shaking can be finicky, and other changes may need to be made to get it fully working. Those changes could be fast-follows to the initial work of getting ESM working.
  • ESM can be transpiled down to CommonJS, and then run through browserify like we do today. But in a few years when browser support for ESM is sufficient, the transpilation can simply be turned off and we can switch to directly taking advantage of native browser module support.

Additional context

In some ways this is the javascript sister issue to #2854.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    On Hold

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions