Esbuild typescript 路径解析

问题描述 投票:0回答:1

我正在使用 bazel 和 esbuild 构建一个 Angular 应用程序。

使用常规导入一切工作正常

import {Foo} from '../../shared/foo'

但是我在 tsconfig 中添加了一些路径别名,如下所示:

    "baseUrl": ".",
    "rootDir": ".",
    "paths": {
      "@core/*": [
        "./src/app/core/*"
      ],
      "@shared/*": [
        "./src/app/shared/*"
      ],
      "@features/*": [
        "./src/app/features/*"
      ]
    }

我现在遇到了此类错误:

error TS2307: Cannot find module '@shared/foo' or its corresponding type declarations.
4 import { Foo } from '@shared/foo';

在我看来,这与 esbuild 无法解析别名路径有关。

ng-esbuild.ts

import { ConsoleLogger, NodeJSFileSystem, LogLevel } from '@angular/compiler-cli';
import { createEs2015LinkerPlugin } from '@angular/compiler-cli/linker/babel';
import { transformFileAsync } from '@babel/core';

const linkerBabelPlugin = createEs2015LinkerPlugin({
  fileSystem: new NodeJSFileSystem(),
  logger: new ConsoleLogger(LogLevel.warn),
  unknownDeclarationVersionHandling: 'error',
  // Must enable JIT for unit tests
  // TODO: would be ideal to only set this for tests
  linkerJitMode: true,
  sourceMapping: false,
});

const ngLinkerPlugin = {
  name: 'ng-linker-esbuild',
  setup(build: any) {
    build.onLoad({ filter: /node_modules/ }, async (args: any) => {
      const filePath = args.path;
      const transformResult = await transformFileAsync(filePath, {
        filename: filePath,
        filenameRelative: filePath,
        plugins: [linkerBabelPlugin],
        sourceMaps: 'inline',
        compact: false,
      });

      if (!transformResult) {
        throw new Error('Babel NG Linker error');
      }

      return { contents: transformResult.code };
    });
  },
};

export default {
  resolveExtensions: ['.mjs', '.js'],
  plugins: [ngLinkerPlugin],
};

和我的 BUILD.bazel

load("@aspect_rules_ts//ts:defs.bzl",  "ts_config", "ts_project")

package(default_visibility = ["//visibility:public"])

ts_config(
  name = "tsconfig",
  src = "tsconfig.json",
  deps = [
    "//:tsconfig"
  ]
)

ts_project(
  name = "ts",
  srcs = ["ngc.esbuild.ts"],
  tsconfig = ":tsconfig",
  deps = [
    "//:node_modules/@angular/compiler-cli",
    "//:node_modules/@babel/core",
    "//:node_modules/@types/babel__core",
    "//:node_modules/@types/node",
  ],
)

genrule(
  name = "ng-esbuild",
  srcs = ["ngc.esbuild.js"],
  outs = ["ngc.esbuild.mjs"],
  cmd = "cp $(location ngc.esbuild.js) $@"
)

我尝试过使用这些插件,但到目前为止还没有成功

angular typescript bazel esbuild bazel-aspect
1个回答
0
投票

我不熟悉 Angular,但我在 esbuild 中遇到了类似的路径解析问题。为了解决这个问题,我开发了 xBuild 包,它支持所有 esbuild 配置和一些配置(ifdef、多重构建 [esm、cjs ...])。

您可以在这里查看该项目:
GitHub:https://github.com/remotex-lab/xBuild
npm:https://www.npmjs.com/package/@remotex-labs/xbuild

© www.soinside.com 2019 - 2024. All rights reserved.