egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
9k stars 217 forks source link

bundle=false,compilerOptions.paths not work!!! #729

Open daolou opened 2 years ago

daolou commented 2 years ago
  1. tsconfig: image

  2. index.ts: image

  3. tsup: image

  4. output: image

Upvote & Fund

Fund with Polar

await-ovo commented 1 year ago

I think this is related to ebuild, which only does path transformation when bundling is enabled.

Note that import path transformation requires bundling to be enabled, since path resolution only happens during bundling. https://esbuild.github.io/content-types/#tsconfig-json

And tsc will also output import statements with aliases in the emitted code.

RedStar071 commented 1 year ago

I think this is related to ebuild, which only does path transformation when bundling is enabled.

Note that import path transformation requires bundling to be enabled, since path resolution only happens during bundling. https://esbuild.github.io/content-types/#tsconfig-json

And tsc will also output import statements with aliases in the emitted code.

is there a way that transforms paths even if bundling is deactivated?

duclet commented 1 year ago

I've ended up adding this to tsup's config to make this work. Not great and probably doesn't cover all use cases but seems to work for me. It basically cheats but looking for ts files, reading the content in and see if there are lines that imports from the desired source and then overwriting it.

    esbuildPlugins: [
        {
            // This allows using the @src absolute path that will map to relative paths
            name: 'absolute-relative-imports',
            setup: (build) => {
                build.onLoad({ filter: new RegExp(`^${__dirname}/src/.+\\.ts$`) }, (args) => {
                    const content = readFileSync(args.path).toString();
                    if (content.includes("from '@src/")) {
                        const relativePath = relative(dirname(args.path), __dirname + '/src');
                        return {
                            contents: content.replaceAll(
                                "from '@src/",
                                relativePath === '' ? "from './" : `from '${relativePath}/`
                            ),
                            loader: 'ts',
                        };
                    }

                    return null;
                });
            },
        },
    ],
duclet commented 1 year ago

So it seems like someone has written a plugin which does a much better job at this: https://github.com/wjfei/esbuild-plugin-tsconfig-paths

The only caveat is that since it is actually parsing the code tree rather than simple string matching, it is much slower.