Skip to content

Commit 0462c1f

Browse files
committed
build(package): ensure NodeJS considers ESM .js files as ESM
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.
1 parent aa1239c commit 0462c1f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

tools/prepare-package.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,14 @@ klawSync(ESM5_ROOT, {
2727
})
2828
.map((item) => item.path.slice(`${__dirname}/${ESM5_ROOT}`.length))
2929
.map((fileName) => {
30-
if (!bo) {return fileName;}
30+
if (!bo) {
31+
return fileName;
32+
}
3133
const fullPath = path.resolve(__dirname, ESM5_ROOT, fileName);
3234
// The file won't exist when running build_test as we don't create the ESM5 sources
33-
if (!fs.existsSync(fullPath)) {return fileName;}
35+
if (!fs.existsSync(fullPath)) {
36+
return fileName;
37+
}
3438
const content = fs.readFileSync(fullPath).toString();
3539
const transformed = bo.transformJavascript({
3640
content: content,
@@ -76,3 +80,9 @@ fs.removeSync(ESM5_ROOT + '/internal/umd.js.map');
7680
fs.removeSync(ESM_ROOT + '/internal/umd.js');
7781
fs.removeSync(ESM_ROOT + '/internal/umd.js.map');
7882
fs.removeSync(TYPE_ROOT + '/internal/umd.d.ts');
83+
84+
// Create `package.json` files for the ESM5 and ESM2015 roots that
85+
// instruct NodeJS to treat `.js` files inside as ESM.
86+
const esmPkgJson = JSON.stringify({ type: 'module', sideEffects: false });
87+
fs.writeFileSync(path.join(ESM5_ROOT, 'package.json'), esmPkgJson);
88+
fs.writeFileSync(path.join(ESM_ROOT, 'package.json'), esmPkgJson);

0 commit comments

Comments
 (0)