huozhi / bunchee

Zero config bundler for ECMAScript and TypeScript packages
https://npmjs.com/bunchee
858 stars 28 forks source link

feat: generate relative imports #538

Closed huozhi closed 3 weeks ago

huozhi commented 3 weeks ago

This will PR generates the relative paths relationship for the JS bundles.

For instance, for the 2 exports which one is relying on the other one, and ./foo is dependent on ./, project name is "my-lib":

- src/
  |- index.ts
  |- foo.ts

Bunchee will output the below structure and use "<project name>/<export path>" as dependency for each bundle to import the other export bundles. e.g. foo.js will import from "my-lib" as it's the ./ export.

- dist/
  |- index.js
  |- foo.js

This output is not ideal cause it might resolve the 2nd module resolving. And some bundler might error (e.g. vite).

After this PR, the output the relative path for all imports and there's no extra module resolving. And we did some smart resolution which also based on the output format, to make sure CJS is only requiring other CJS bundles and ESM can resolve other ESM bundles.

e.g.

  1. default ESM case
// ./dist/foo.js

import core from './index.js'
  1. dual package case
// ./dist/foo.cjs

const code = require('./index.cjs')
// ./dist/foo.mjs

import core from './index.mjs'
  1. types

Types will also be smartly resolved like above, but since we could have import.types or require.types conditions, or simply types conditions, so we'll resolve twice to make sure it's able to be resolved properly matching with the format.

Resolves #511