I had to move to ESM — Here is what I did

Emil Krebs
2 min readOct 18, 2023

Recently I saw Yeoman migrated to a pure ESM package. My Project Generator-Discord uses Yeoman so I had the choice to upgrade to ESM or stay on an outdated version— so I moved to ESM. In the following, I will walk you through the process of moving your package to ESM.

What is ESM

ESM stands for ECMAScript Module and is JavaScript’s approach to implementing a standard module system. Most of us are familiar with the following examples:

import React, { useRef, useEffect } from 'react';

export default class Terminal extends Component<TerminalProps, TerminalState> {
...
}

Why move to ESM

You should move to ESM for improved code modularity, better dependency management, and enhanced support for static analysis and tree-shaking in modern JavaScript development as listed below:

  • Improved code modularity
  • Better dependency management
  • Enhanced support for static analysis
  • Better tree-shaking capabilities

How did I move to ESM

First I needed to make some changes to package.json:

  1. Add "type": "module"
  2. Replace "main": "./app/index.js" with "exports": "./app/index.js"
  3. Modify the "engines" property to specify Node.js 16 "node": ">=16.0.0"

Result:

{
"name": "generator-discord",
"displayName": "Generator-Discord",
"version": "1.3.0",
"type": "module",
"exports": "./app/index.js",
"engines": {
"node": ">=16.0.0"
},
...
}

Because I am using TypeScript I needed to make some changes to tsconfig.json so TypeScript does output ESM as well by adding:

...
"module": "Node16",
"moduleResolution": "Node16",
...

I also needed to change my code a bit, because __dirname and __filename does not exist in ESM. So I used import.meta.url instead:

const currentUrl = new URL('../', import.meta.url).pathname;

Conclusion

After these minor changes, I finally moved my project Generator-Discord to ESM. I hope, I was able helping a bit with the process of moving your project to ESM. Keep in mind that Generator-Discord is a relatively small project so it was a small task— larger projects maybe require more dramatic changes.

--

--