Skip to content

How to extract or minify shared code (__toCommonJS) in commonjs format? #2957

@noyobo

Description

@noyobo

Each file has a shared part. First, I need to use esm to build it once (because tree shaking only work in esm format), and then convert it into cjs format and publish it to the production environment(esmodule is not supported). When converting to cjs, a lot of repetitive code is generated.

// 1. Extract shared code
const result = await esbuild.build({
  entryPoints:['a.js', 'b.js', ....],
  bundle: true,
  splitting: true,
  format: 'esm',
  write: false
})

// 2. Convert to cjs format
for (const file of result.outputFiles) {
  const result = await esbuild.transform(file.text, {
    format: 'cjs',
  });
  fs.writeFileSync(file.path, result.code)
}

When converting to commomjs format, there will be a lot of repeated __toCommonJS

how to extract __toCommonJS ?

export function sum() {
  // 
}

output

+ var __defProp = Object.defineProperty;
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
+ var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+ };
+ var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+ };
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

+ // project/index.ts
+ var project_exports = {};
+ __export(project_exports, {
+  sum: () => sum
+ });
+ module.exports = __toCommonJS(project_exports);
function sum() {
}

Or is there a more streamlined way like swc:

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions