Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I make tsup resolve my typescript absolute import paths? #905

Open
isomorpheric opened this issue May 14, 2023 · 9 comments
Open

Comments

@isomorpheric
Copy link

isomorpheric commented May 14, 2023

👋 Hi and thank you so much for your work ❤️ 🤟🏼

Description

tsup is not resolving typescript absolute imports. I have a tsconfig.json that defines multiple absolute imports (see below). tsup bundles it without resolving for those absolute imports, so it causes errors when consuming the lib in other projects.

In your docs, I can see NormalizedOptions - which uses tsconfigResolvePaths - but when I try to put it in my config (see below) typescript gets angry 😠:

'tsconfigResolvePaths' does not exist in type 'Options | Options[] | ((overrideOptions: Options) => MaybePromise<Options | Options[]>)'

tsconfig.json:

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@services/*": [
        "./services/*"
      ],
      "@vendors/*": [
        "./vendors/*"
      ],
// ....
    },

tsup.config.json:

import { defineConfig } from 'tsup';

export default defineConfig({
  entry: {
    index: 'index.ts',
    'services/marketing/index': 'services/marketing/index.ts',
    'vendors/index': 'vendors/index.ts',
  },
  tsconfig: './tsconfig.json',
  splitting: false,
  sourcemap: true,
  clean: true,
});

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@wojtekKrol
Copy link

have the same issue

@dheerajsinghnagdali
Copy link

I have the same issue as well.

@undermuz
Copy link

have the same issue

@PureSci
Copy link

PureSci commented Mar 20, 2024

this is still an issue

@mehrangta
Copy link

Any updates/workarounds on this ?

mikoloism added a commit to wonize/biruni that referenced this issue Apr 30, 2024
- the `tsup` builder not support `tsconfig.compilerOptions.paths`
	issue egoist/tsup#905
@PHILLIPS71
Copy link

I'm encountering the same problem and have been using https://github.com/benyap/resolve-tspaths as a workaround. However, it doesn't function when minify is enabled 😞. It would be great if this feature were natively supported and working properly.

@ThijsZijdel
Copy link

bump..

@Tomas2D
Copy link

Tomas2D commented Aug 21, 2024

bump

@Tomas2D
Copy link

Tomas2D commented Aug 22, 2024

Since I have emitDecoratorMetadata: true in my tsconfig, tsup uses @swc/core to process it. But the problem is that tsup does not propagate related TSConfig information to the swc (here is the SWC plugin that I am talking about). However, there is a way how to do this.

My updated tsup.config.ts (simplified)

import { defineConfig } from "tsup";
import packageJson from "./package.json";
import swc, { JscConfig } from "@swc/core";
import type { JscTarget } from "@swc/types"; // 
import path from "node:path";

import tsConfig from "./tsconfig.json"; // important

export default defineConfig({
  entry: ["src/**/*.{ts,js}", "!src/**/*.test.ts"],
  tsconfig: "./tsconfig.json",
  sourcemap: true,
  dts: true,
  format: ["esm", "cjs"],
  plugins: [
    {
      name: "override-swc",
      esbuildOptions: (options) => {
        const plugin = options.plugins?.find((p) => p.name === "swc");
        if (plugin) {
          // Original Source: https://github.com/egoist/tsup/blob/49c11c3073ce977a01c84e7848fc070d5de0a652/src/esbuild/swc.ts#L14-L67
          // Reason: tsup does not provide a way to modify 'jsc' config
          plugin.setup = (build) => {
            // Force esbuild to keep class names as well
            build.initialOptions.keepNames = true;

            build.onLoad({ filter: /\.[jt]sx?$/ }, async (args: any) => {
              const isTs = /\.tsx?$/.test(args.path);

              const jsc: JscConfig = {
                parser: {
                  syntax: isTs ? "typescript" : "ecmascript",
                  decorators: true,
                },
                transform: {
                  legacyDecorator: true,
                  decoratorMetadata: true,
                },
                baseUrl: path.resolve(__dirname, tsConfig.compilerOptions.baseUrl || "."),  // this was missing
                paths: tsConfig.compilerOptions.paths,  // this was missing
                keepClassNames: true,
                target: (tsConfig.compilerOptions.target || "es2022").toLowerCase() as JscTarget,
              };

              const result = await swc.transformFile(args.path, {
                jsc,
                sourceMaps: true,
                configFile: false,
                swcrc: false,
              });

              let code = result.code;
              if (result.map) {
                const map: { sources: string[] } = JSON.parse(result.map);
                // Make sure sources are relative path
                map.sources = map.sources.map((source) => {
                  return path.isAbsolute(source)
                    ? path.relative(path.dirname(args.path), source)
                    : source;
                });
                code += `//# sourceMappingURL=data:application/json;base64,${Buffer.from(
                  JSON.stringify(map),
                ).toString("base64")}`;
              }
              return {
                contents: code,
              };
            });
          };
        }
      },
    },
  ],
  treeshake: true,
  shims: true,
  skipNodeModulesBundle: true,
  legacyOutput: false,
  bundle: false,
  splitting: false,
  silent: false,
  clean: true
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants