【问题标题】:Is it possible to include a json file when using TypeScript with a tsconfig.json file?将 TypeScript 与 tsconfig.json 文件一起使用时是否可以包含 json 文件?
【发布时间】:2017-07-14 06:25:07
【问题描述】:

有没有办法让 TypeScript 编译器也将没有 ts 或 tsx 扩展名的内容文件复制到输出目录?

例如,我的 tsconfig.json 看起来像:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": true,
        "outDir": "../../dist",
        "types": [
        ]
    },
    "include": [
        "file1.ts",
        "config.json"
    ],
    "exclude": [
        "../../node_modules"
    ]
}

我希望 config.json 最终出现在我的 ../../dist 目录中,但这没有发生。 TypeScript 没有内容文件的概念吗?

【问题讨论】:

标签: json typescript


【解决方案1】:

我遇到了同样的问题,解决方法是添加:

“源路径/**/*.json”

保存到“包含”数组中:

"源路径/**/*"

例子:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "resolveJsonModule": true,
    "incremental": true
  },
  "include":[ 
    "src/**/*",
    "src/**/*.json",
  ],
}

【讨论】:

    【解决方案2】:

    这可以通过在编译器选项中设置"resolveJsonModule": true并将"source-path/**/*.json"添加到include数组tsconfig.json中来实现

    【讨论】:

    • 我的"include" 属性中有"source-path/**/*",但它不起作用。正如Official tsconfig.json documentation 所说:If a segment of a glob pattern includes only * or .*, then only files with supported extensions are included (e.g. .ts, .tsx, and .d.ts by default with .js and .jsx if allowJs is set to true).
    • @JRadness 这对我不起作用。 tsconfig.json 中还有其他编译器选项吗?
    • @th3r1singking 这是我目前的整个文件{ "compilerOptions": { "experimentalDecorators": true, "resolveJsonModule": true, "allowJs": true, "target": "es6", "jsx": "react", "moduleResolution": "node", "module": "commonjs", "noImplicitAny": true, "outDir": "dist", }, "include": [ "src/**/*" ] }
    • 请注意"resolveJsonModule": true 只复制imported json 文件。它不会复制 all json 文件或 required json 文件。
    • 这里奇怪的是resolveJsonModule: true应该自己工作,但我发现你也必须使用**/*.json。那是**/* 是不够的。所以你需要两个......
    【解决方案3】:

    一种解决方法是将json文件制作成普通的js文件,正常require/import,在tsconfig.json的“compilerOptions”中添加"allowJs" : true

    【讨论】:

    • 如果您遵循该路径,您还可以将其转换为 config.ts 文件,例如export const config = { ... config.json ... }。而且您不需要设置allowJs 选项。
    【解决方案4】:

    不,tsc 命令的作用只是编译 .ts 文件。它不具备像 gulpgruntwebpack 这样的构建系统可以处理的构建相关任务的能力。

    有关更多信息,请参阅此类似问题:Angular 2 + Typescript compiler copy html and css files

    【讨论】:

    • 应该注意我的答案不再正确。请参阅下面@Arun-Reddy 获得的更高票数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多