Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support commonjs #36

Closed
11 of 13 tasks
Tracked by #15
underfin opened this issue Oct 8, 2023 · 0 comments
Closed
11 of 13 tasks
Tracked by #15

support commonjs #36

underfin opened this issue Oct 8, 2023 · 0 comments
Assignees

Comments

@underfin
Copy link
Contributor

underfin commented Oct 8, 2023

Summary

As description of #35, we will following esbuild bundle commonjs strategy.

Linker

  • iter the import records of all modules to identify which module should be wrapped.
  • create binding symbol for esm module import cjs module

Module codegen

Wrap module to lazy execute

  • commonjs module
module.exports = 1
// compiled
var require_a = __commonJS({
  "a.js"(exports, module) {
    module.exports = 1;
  }
});
  • the esm module which imported by commonjs
export const a = 1;
// compiled
var a; 
var init_b = __esm({
  "b.js"() {
    a = 1;
  }
});

Commonjs module codegen

  1. wrapped module with __commonJS
  2. rewrite require call to init module expr call
  • require esm module
require('esm');
// compiled
var require_a = __commonJS({
  "a.js"(exports, module) {
     (init_esm(), __toCommonJS(esm_exports));
  }
});
  • require cjs module
require('cjs');
// compiled
var require_a = __commonJS({
 "a.js"(exports, module) {
   require_cjs();
 }
});

Esm module codegen

  • rewrite import cjs module
import cjs from './cjs'
console.log(cjs)
// compiled
var import_cjs = __toESM(require_cjs());
console.log(import_cjs.default)
  • rewrite import wrapped esm module
import esm from './esm'
console.log(esm)
// compiled
init_esm()
console.log(esm)

Wrapped esm module codegen

  • the import declaration is same as esm module
  • wrapped module with __esm
  • hoisted named declaration function
export function a(){}
// compiled
function a(){}
var b_ns = {
   get a () => a
}
var init_b = __esm({
  "b.js"() {
  }
});
  • hoisted default declaration function
export default function a(){}
// compiled
function a(){}
var b_ns = {
   get default () => a
}
var init_b = __esm({
  "b.js"() {
  }
});
  • hoisted top-level symbol definition, including namespace definition
export default  1
export const a = 1
// compiled
var a, b_default;
var b_ns = {
   get default () => b_default,
   get a() => a
}
var init_b = __esm({
  "b.js"() {
      b_default = 1
      a = 1
  }
});

Implemention

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants