Skip to content

Commit

Permalink
build(package): ensure NodeJS considers ESM .js files as ESM
Browse files Browse the repository at this point in the history
NodeJS treats JavaScript files as ESM when one of the following is true:

 * The file is explicitly named `.mjs`
 * The file is part of a directory where the closest `package.json` has
   `type: module`.

Both things are not applying for the ESM output in `dist/esm` and
`dist/esm5` so these ESM artifacts cannot be used directly in NodeJS
because NodeJS will attempt loading them as CommonJS.

Note that this was not noticeable with e.g. bundlers like Webpack
as those do not rely on the NodeJS semantics for "detecting" ESM.
  • Loading branch information
devversion committed Dec 11, 2022
1 parent aa1239c commit 0462c1f
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions tools/prepare-package.js
Expand Up @@ -27,10 +27,14 @@ klawSync(ESM5_ROOT, {
})
.map((item) => item.path.slice(`${__dirname}/${ESM5_ROOT}`.length))
.map((fileName) => {
if (!bo) {return fileName;}
if (!bo) {
return fileName;
}
const fullPath = path.resolve(__dirname, ESM5_ROOT, fileName);
// The file won't exist when running build_test as we don't create the ESM5 sources
if (!fs.existsSync(fullPath)) {return fileName;}
if (!fs.existsSync(fullPath)) {
return fileName;
}
const content = fs.readFileSync(fullPath).toString();
const transformed = bo.transformJavascript({
content: content,
Expand Down Expand Up @@ -76,3 +80,9 @@ fs.removeSync(ESM5_ROOT + '/internal/umd.js.map');
fs.removeSync(ESM_ROOT + '/internal/umd.js');
fs.removeSync(ESM_ROOT + '/internal/umd.js.map');
fs.removeSync(TYPE_ROOT + '/internal/umd.d.ts');

// Create `package.json` files for the ESM5 and ESM2015 roots that
// instruct NodeJS to treat `.js` files inside as ESM.
const esmPkgJson = JSON.stringify({ type: 'module', sideEffects: false });
fs.writeFileSync(path.join(ESM5_ROOT, 'package.json'), esmPkgJson);
fs.writeFileSync(path.join(ESM_ROOT, 'package.json'), esmPkgJson);

0 comments on commit 0462c1f

Please sign in to comment.