Skip to content

Commit 36211f3

Browse files
authored
better commonjs support (#1007)
1 parent 24bb288 commit 36211f3

File tree

1 file changed

+18
-2
lines changed
  • packages/repl/src/lib/workers/bundler/plugins

1 file changed

+18
-2
lines changed

packages/repl/src/lib/workers/bundler/plugins/commonjs.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,31 @@ const plugin: Plugin = {
2020
});
2121

2222
const requires: string[] = [];
23+
const exports: string[] = [];
2324

2425
walk(ast as Node, null, {
25-
CallExpression: (node) => {
26+
CallExpression: (node, context) => {
2627
if (node.callee.type === 'Identifier' && node.callee.name === 'require') {
2728
if (node.arguments.length !== 1) return;
2829
const arg = node.arguments[0];
2930
if (arg.type !== 'Literal' || typeof arg.value !== 'string') return;
3031

3132
requires.push(arg.value);
3233
}
34+
35+
context.next();
36+
},
37+
AssignmentExpression: (node, context) => {
38+
if (node.operator !== '=') return;
39+
if (node.left.type !== 'MemberExpression') return;
40+
if (node.left.object.type !== 'Identifier' || node.left.object.name !== 'exports') return;
41+
if (node.left.computed || node.left.property.type !== 'Identifier') return;
42+
43+
exports.push(
44+
`export const ${node.left.property.name} = module.exports.${node.left.property.name};`
45+
);
46+
47+
context.next();
3348
}
3449
});
3550

@@ -44,7 +59,8 @@ const plugin: Plugin = {
4459
require,
4560
`const exports = {}; const module = { exports };`,
4661
code,
47-
`export default module.exports;`
62+
`export default module.exports;`,
63+
exports.join('\n')
4864
].join('\n\n');
4965

5066
return {

0 commit comments

Comments
 (0)