Skip to content

Commit

Permalink
Hack: leave .mjs as esm
Browse files Browse the repository at this point in the history
  • Loading branch information
samouri committed May 11, 2021
1 parent 879ff95 commit 2aa6272
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions build-system/common/esbuild-babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,53 @@ function getEsbuildBabelPlugin(
build.onLoad({filter: /\.[cm]?js$/, namespace: ''}, async (file) => {
const filename = file.path;
const {contents, hash} = await batchedRead(filename, optionsHash);
const transformed = await transformContents(filename, contents, hash, {
...babelOptions,

const transformed = await transformContents(
filename,
filenameRelative: path.basename(filename),
});
contents,
hash,
getFileBabelOptions(babelOptions, filename)
);
return {contents: transformed};
});
},
};
}

/**
* @param {!Object} babelOptions
* @param {string} filename
* @return {!Object}
*/
function getFileBabelOptions(babelOptions, filename) {
// Patch for leaving .mjs files as esm, since esbuild will break when trying
// to process a .mjs file that contains CJS exports. This function is called after
// babel.loadOptions, therefore all of the plugins from preset-env have already been applied.
// and must be disabled individually.
if (filename.endsWith('.mjs')) {
const plugins = [...babelOptions.plugins];
const toRemove = [
'transform-modules-commonjs',
'proposal-dynamic-import',
'syntax-dynamic-import',
'proposal-export-namespace-from',
'syntax-export-namespace-from',
];
for (const plugin of toRemove) {
const pluginIndex = plugins.findIndex(({key}) => key === plugin);
plugins.splice(pluginIndex, 1);
}

babelOptions = {...babelOptions, plugins};
}

return {
...babelOptions,
filename,
filenameRelative: path.basename(filename),
};
}

module.exports = {
getEsbuildBabelPlugin,
};

0 comments on commit 2aa6272

Please sign in to comment.