首页 > 解决方案 > 将“Typescript”文件夹构建到遗留的 javascript 文件架构

问题描述

我正在开发一个最初用纯 Javascript 编写的项目。我在根级别添加了一个 Typescript 文件夹,其中包含与原始 javascript 相同的结构。文件结构如下所示:

|_ build
|  |_ automatically generated js files from Meta and src using build command
|
|_ meta
|  |_ foo.js, bar.js
|
|_ src
|  |_ baz.js
|
|_ typescript
|  |_ meta
|     |_ foo.ts, bar.ts
|  |_ src
|     |_ baz.ts

当我运行 tsc 时,我希望 typescript 目录中的所有 Typescript 文件都编译成它们在 Typescript 目录中存在的相同结构到根目录。但是,我看到的大多数使用 outDir 的示例都有构建到特定构建文件夹的内容。

{
  "compilerOptions": {
    "sourceMap": false,
    "noImplicitAny": true,
    "module": "es6",
    "moduleResolution": "node",
    "allowJs": true,
    "target": "ES2020",
    "lib": ["ES2018"],
    "allowSyntheticDefaultImports": true
    "outDir" : "" // what can be here to say "use include file structure - typescript dir?
  },
  "exclude": ["node_modules"],
  "include": ["typescript/**/*"]
}

我无法将 Javascript 目录包装到“dist”文件夹中。我应该如何构建我的 tsconfig 以构建到根级别,匹配打字稿目录中的相同目录?

标签: javascripttypescriptmigration

解决方案


回顾一下您的要求:

|_ meta // emit js files for typescript/meta here
|_ src  // emit js files for typescript/src here
|_ typescript // root folder for all .ts source files
|  |_ meta
|     |_ foo.ts, bar.ts
|  |_ src
|     |_ baz.ts

为此,我们可以调整tsconfig.json

{
  "compilerOptions": {
    // ...
    "outDir": ".",
    "rootDir": "typescript"
  },
  "include": ["typescript/**/*"],
  "exclude": ["node_modules", "src", "meta", "build"],
}

然后所有输入.ts文件将在以下路径中发出(相对于tsconfig.json):

emit-path: <outDir>/<filePath> minus <rootDir>  (rootDir chopped off from file path)

Example: ./typescript/src/baz.ts  -->  ./src/baz.js

我们可以省略rootDir配置选项:

默认值:所有非声明输入文件的最长公共路径。当 TypeScript 编译文件时,它在输出目录中保持与输入目录中相同的目录结构。

尽管将其明确化是一个好习惯,但如果输入文件的位置有问题,编译器会触发错误。


推荐阅读