unbuild icon indicating copy to clipboard operation
unbuild copied to clipboard

Unknown reason why the import in the generated file does not have the .mjs suffix.

Open DemoMacro opened this issue 3 years ago • 3 comments

The configuration is as follows.

import { defineBuildConfig } from "unbuild";

export default defineBuildConfig({
  declaration: true,
  entries: ["src/"],
});

Generate the wrong import in the file.

// dist/cli.mjs
import {} from "./example";

This should normally be the case.

// dist/cli.mjs
import {} from "./example.mjs";

I don't understand the reason for the problem, but when I use the function in this way it is normal.

// src/cli.ts
import * as exampleImport from "./example";

exampleImport.runCommand()
// dist/cli.mjs
import * as exampleImport from "./example.mjs";

exampleImport.runCommand()

DemoMacro avatar Jun 03 '22 18:06 DemoMacro

I think I found a magical reason for a line break due to too many imported functions, at which point the .mjs suffix would not be generated.

// This can cause problems.
import {
  exampleFunc1,
  exampleFunc2,
  exampleFunc3,
  exampleFunc4,
  exampleFunc5,
} from "./example";
// This, however, does not.
import { exampleFunc1, exampleFunc2, exampleFunc3 } from "./example.mjs";

DemoMacro avatar Jun 03 '22 19:06 DemoMacro

The same issue, i use prettier to format the codes. Maybe I have to add a .prettierrc to avoid a line break.

yzqdev avatar Jun 25 '22 18:06 yzqdev

Thanks for this issue. This is because mkdist (library unbuild uses for per-file transform) uses a simple regex to add the explicit extension (src) and it doesn't covers multiline. If your src uses .mjs, i strongly advice that you always add explicit extension in the source code imports too as this is a part of ESM syntax spec. For typescript is however not possible...

Upstream issue to fix: https://github.com/unjs/mkdist/issues/45

pi0 avatar Jun 27 '22 09:06 pi0

https://github.com/unjs/mkdist/pull/120 should cover most of cases. Please ping to reopen or make a new issue with reproduction if still in some cases this rewrite is not happening.

pi0 avatar Jul 18 '23 16:07 pi0