Skip to content

Support rewriting specifiers in dynamic imports for transform entry mode #92

Description

@Yizack

Describe the feature

Hi!

I was trying the transform entry type and noticed that import specifier rewriting works for static imports, but not for dynamic imports.

Example setup:

src/hello-world.ts

export default () => {
  return "hello-world";
};

src/index.ts

const { default: helloWorld } = await import("./hello-world.ts");
console.log(helloWorld());

build.config.ts

import { defineBuildConfig } from "obuild/config";

export default defineBuildConfig({
  entries: [
    {
      type: "transform",
      input: "./src",
      outDir: "./dist",
      dts: false
    }
  ]
});

The generated output in dist/index.mjs dynamic import remains:

await import("./hello-world.ts");

instead of:

await import("./hello-world.mjs");

Even though dist/hello-world.mjs file was generated.

I was wondering if dynamic imports are intentionally excluded, if they are I may be completely wrong here.

Would you be open to adding support for rewriting dynamic import specifiers as well? For example, adding a TransformEntry option like:

rewriteDynamicImportExtensions: true

(or another name that better fits) could enable transforming .ts extensions from dynamic imports

Solution

I tried implementing this change in a fork, it worked for me but I'm not an expert in build tools so I'm not sure if this'd be the right approach as it only rewrites string literals

if (entry.rewriteDynamicImportExtensions) {
for (const dynamicImport of parsed.module.dynamicImports) {
const { start, end } = dynamicImport.moduleRequest;
const match = sourceText.slice(start, end).match(/^(['"])(.*?)\1$/);
if (!match) {
continue;
}
const moduleId = match[2];
if (moduleId.endsWith(".mjs")) {
continue;
}
rewriteSpecifier({ value: moduleId, start, end });
}

Thanks!

Additional information

  • Would you be willing to help implement this feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions