ECMAScript Modules

From https://nodejs.org/api/esm.html#introduction:

ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.

Starter ECMAScript Module Template

Extension comes with a default ECMAScript Module template for new projects, which you can use as a starting point for your next ECMAScript Module-based Extension. This is the easiest way to have ECMAScript Modules integrated with Extension.

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=esm

Usage With An Existing Extension

To make Extension recognize all files as ECMAScript Modules, define "type": "module" in your package.json.

// package.json
{
  "name": "my-extension",
  "version": "1.0",
  "description": "My Extension Example.",
+ "type": "module"
  "devDependencies": {
    "extension": "latest"
  },
  "scripts": {
    "dev": "extension@latest dev",
    "start": "extension start",
    "build": "extension@latest build"
  }
}

Differences From Non-ECMAScript Modules

ECMAScript Modules have some differences from CommonJS modules. See below.

Relative requests must include a filename and file extension (e.g. *.js or *.mjs).

Except for modules imported from your package.json, all imports must include its file extension.

// my-file.mjs

// React doesn't need a file extension since it's imported from package.json
import React from 'react'

// myImport needs a file extension since it's a locally imported module
+ import myImport from './myImport.js'
- import myImport from './myImport'

Only the "default" export can be imported from non-ESM. Named exports are not available.

If the file you are working on is not an ESM but the file you are importing is, then it must use a default import to work.

// my-file.js -- not a module.

// myImport is a module. It only works via default import/export.
+ import myDefaultExport from './myImport.mjs'
- import {myExportedMethod} from './myImport.mjs'

CommonJS Syntax is not available

Attempting to use CommonJS syntax such as require, module, exports, __filename, __dirname will result in an error.

Next Steps

  • Learn how Extension works with extensions using CSS Modules.