typescript turborepo包意外的令牌导出

ehxuflar  于 2023-08-08  发布在  TypeScript
关注(0)|答案(2)|浏览(104)

我有一个名为project-types的自定义包,我在包之间共享我的类型
当我将简单的类导入到我的nestjs项目中时,typescript编译得很好,但是当涉及到运行时和执行JavaScript时,它说:

server:dev: D:\Program\net-autism\packages\project-types\index.ts:1
server:dev: export * from "./authentication";     
server:dev: ^^^^^^
server:dev: 
server:dev: SyntaxError: Unexpected token 'export'
server:dev:     at Object.compileFunction (node:vm:352:18)
server:dev:     at wrapSafe (node:internal/modules/cjs/loader:1031:15)
server:dev:     at Module._compile (node:internal/modules/cjs/loader:1065:27)
server:dev:     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)      
server:dev:     at Module.load (node:internal/modules/cjs/loader:981:32)

字符串
package.json

{
  "name": "project-types",
  "version": "0.0.5",
  "main": "./index.ts",
  "types": "./index.ts",
  "type": "module",
  "license": "MIT",
  "scripts": {
    "lint": "eslint *.ts*"
  },
  "devDependencies": {
    "eslint": "^7.32.0",
    "eslint-config-custom": "*",
    "tsconfig": "*",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "class-transformer": "^0.5.1",
    "class-validator": "^0.13.2"
  }
}


使用方法:

import { Body, Controller, Post } from '@nestjs/common';
import { LoginDto } from 'project-types';

@Controller('auth')
export class AuthController {
  constructor() {}

  @Post('login')
  async login(@Body() credentials: LoginDto) {}

  @Post('register')
  async register() {}
}

km0tfn4u

km0tfn4u1#

我也是刚刚碰到这个问题。从我所知道的,当你构建你的消费应用程序时,它并没有从你的类型包中转译Typescript。
对于NextJS项目,有一个npm包可以解决这个问题https://www.npmjs.com/package/next-transpile-modules
然而,由于我有一个NestJS项目,你需要自己转译类型包。这是我的设置:

packages/project-types/package.json

{
  ...
  // entry point is now the transpiled version of your code
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "type": "commonjs",
  "scripts": {
    "build": "tsc",
  ...
}

字符串

packages/project-types/tsconfig.json

{
  "include": ["."],
  "exclude": ["dist", "build", "node_modules"],
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "./dist"
  }
}

apps/nest-project/tsconfig.json

{
  ...
  "module": "commonjs",
  ...
}


然后,您可以配置turbo.json,以确保所有依赖包都预先构建拓扑依赖关系。示例摘自Turbo文档:

"pipeline": {
    "build": {
      // "A package's `build` command depends on its dependencies'
      // and devDependencies' `build` commands being completed first"
      "dependsOn": ["^build"]
    }
    // ... omitted for brevity
  }


希望能帮上忙。
[更新]
示例repo

fumotvh3

fumotvh32#

更好的解决办法是像帕特里克·肯扬那样,
并在ts-config中添加以下内容:
您的软件包tsconfig.json:

"compilerOptions":{
   ...
   "paths": {
     "your_package_name": ["./src/index"]
   }

字符串
您的应用tsconfig.json

"compilerOptions":{
   ...
    "paths": {

           "dto": ["../../../packages/your_package_name/src/index.ts"]
       }

相关问题