TypeScript monorepo`导入类型`解析错误

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

_________ 设置 _________

我有一个 pnpm 工作区,其结构如下:

workspace/
├── apps/
├───── nextjs-app/
├──────── package.json 
├──────── tsconfig.json  
├──────── ...
├── packages/
├───── api/
├──────── package.json 
├──────── tsconfig.json 
├──────── index.ts
├── tsconfig.base.json
└── package.json

nextjs-app
是一个 Next.js 启动器,预配置了所有 TS,除了我修改了所有
tsconfig.json
文件。以下是三个 TS 配置文件的内容:

./tscofnig.base.json

{
  "compilerOptions": {
    "target": "es2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "noUncheckedIndexedAccess": true,
    "experimentalDecorators": true
  }
}

./apps/nextjs-app/tsconfig.json

{
  "extends": "../../tsconfig.base.json",
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.cjs", "**/*.mjs"],
  "exclude": ["node_modules"]
}

./packages/api/tsconfig.json

{
  "extends": "../../tsconfig.base.json",
  "include": ["index.ts"]
}

此外,

./packages/api/package.json
还包含以下两个设置:

{
  ...
  "name": "@my-app/api",
  "main": "./index.ts",
  "types": "./index.ts"
  ...
}

最后,为了在我的 NextJS 项目中安装工作区包,我运行以下命令:

pnpm --filter nextjs-app add @my-app/api@workspace:*

_________ 问题 _________

如果 API 包中有

export const foo = 'bar';
,我可以使用
import { foo } from '@my-app/api';
轻松地将其导入到我的 Next.js 应用程序中的任何位置。这一切都很好。

但是如果我尝试在 API 包中使用

import type
export type
语法,则会收到以下错误:

../../packages/api/index.ts
Module parse failed: Unexpected token (14:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export const foo = 'bar';
| 
> export type Foo = 'bar';
|

否则这种情况永远不会发生,也就是说,只要这一切发生在 NextJS 项目中,我就能够

import type
export type
。但是当我在 API 包中执行此操作时,我收到错误。

node.js typescript webpack next.js tsconfig
1个回答
0
投票

我遇到了类似的事情。对于您给定的配置,我猜是

"noEmit": true

在你的基础 tsconfig 中将阻止输出。您可以尝试在

outDir
中定义显式
noEmit: false
以及
/api/tsconfig.json
,这将允许您查看运行
tsc
编译器的结果。

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