From 0462c1fa1881e6c736f219ef61c6e7280bf8bbf6 Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Fri, 9 Dec 2022 14:52:41 +0000 Subject: [PATCH] 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. --- tools/prepare-package.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tools/prepare-package.js b/tools/prepare-package.js index ec43e10d41..a1c250a834 100644 --- a/tools/prepare-package.js +++ b/tools/prepare-package.js @@ -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, @@ -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);