告诉打字稿编译json文件 [英] tell typescript to compile json files

查看:78
本文介绍了告诉打字稿编译json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用导入json文件时,打字稿编译器工作正常

const tasks = require('./tasks.json')

但是,当我运行tsc时,输出目录不包含任何tasks.json文件,从而导致运行时错误.

是否可以告诉编译器应复制所有json文件,还是应该手动将所有json文件复制/粘贴到dist目录?

我的tsc编译器选项当前读取

  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "sourceMap": true,
    "noImplicitAny": true,
    "removeComments": false,
    "outDir": "./dist/",
    "sourceMap": true,
    "pretty": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "sourceMap": true
  },

谢谢!

解决方案

问题

对于想要复制所有 JSON文件的人来说,使用TypeScript确实很困难.即使使用"resolveJsonModule": truetsc也将仅复制import直接引用的.json文件.

这是一些想要执行动态运行时require()的示例代码.仅当所有JSON文件都已复制到dist/文件夹(tsc 拒绝这样做.

// Works
import * as config from './config.default.json';

const env = process.env.NODE_ENV || 'development';

const envConfigFile = `./config.${env}.json`;

if (fs.existsSync(envConfigFile)) {
  // Does not work
  const envConfig = require(envConfigFile);
  Object.assign(config, envConfig);
}

解决方案1:将json文件保留在src树之外(推荐)

假设您具有/src//dist/文件夹,则可以将JSON文件保留在项目的/文件夹中.然后位于/src/config/load-config.ts的脚本可以在运行时执行此操作:

const envConfig = require(`../../config.${env}.json`);

// Or you could read manually without using require
const envConfigFile = path.join(__dirname, '..', '..', `config.${env}.json`);
const envConfig = JSON.parse(fs.readFileSync(envConfigFile, 'utf-8'));

这是最简单的解决方案.您只需要确保在生产环境中将必要的配置文件放置在适当的位置即可.

当您确实希望将配置文件保存在src/文件夹中并将它们显示在dist/文件夹中时,其余的解决方案将解决这种情况.

解决方案2:导入所有可能的文件

对于上述示例,我们可以这样做:

import * as config from './config.default.json';
import * as testingConfig from './config.testing.json';
import * as stagingConfig from './config.staging.json';
import * as productionConfig from './config.production.json';

这应该导致将指定的json文件复制到dist/文件夹中,因此我们的require()现在应该可以使用了.

缺点:如果有人要添加新的.json文件,则他们还必须添加新的导入行.

解决方案3:分别复制json文件(推荐)

您可以添加> cpy-cli 到您的构建过程,在tsc完成后将所有.json文件复制到dist/文件夹中.

这假定您使用npm run build或类似的东西进行构建.

例如:

$ npm install --save-dev cpy-cli

// To copy just the json files, add this to package.json
"postbuild": "cpy --cwd=src --parents '**/*.json' ../dist/",

// Or to copy everything except TypeScript files
"postbuild": "cpy --cwd=src --parents '**/*' '!**/*.ts' ../dist/",

现在npm run build应该运行tsc,然后再运行cpy.

缺点:需要额外的devDependency.而且,您必须将此部分纳入构建过程.

解决方案4:使用js文件代替json文件

或者,不要使用.json文件.而是将它们移到.js文件中,并在tsconfig.json中启用"allowJs": true.然后tsc将为您复制文件.

您的新.js文件将需要如下所示:module.exports = { ... };

在这里推荐.

注意:要启用"allowJs": true,您可能需要添加"esModuleInterop": true"declaration": false,甚至可能添加"skipLibCheck": true.这取决于您现有的设置.

还有其他问题(对不起,我没有对此进行测试):

  • 如果配置文件没有全部由其他文件静态引用,tsc会转换您的配置文件吗?您的文件或其文件夹可能需要在tsconfig.jsonfilesinclude选项中明确引用.

解决方案5:使用ts文件而不是json文件

听起来很简单,但仍有一些需要考虑的问题:

  • 您的配置文件现在看起来像这样:const config = { ... }; export default config;

  • 请参阅上面有关files/include选项的注释.

  • 如果在运行时动态加载配置文件,请不要忘记它们将被转换为.js文件.因此,不要尝试require() .ts文件,因为它们将不存在!

  • 如果有人要更改配置文件,则应该进行全新的tsc构建.他们可能会破坏dist文件夹中已转译的.js文件,但是应避免这样做,因为将来的构建可能会覆盖所做的更改.

测试

尝试此操作时,请 确保在构建之间清除您的dist/文件夹和tsconfig.tsbuildinfo文件,以正确测试该过程. >

(tsc并不总是清除dist/文件夹,有时它只是向其中添加新文件.因此,如果不删除它们,早期实验中遗留的旧文件可能会产生误导性的结果!)

The typescript compiler works fine when I import a json file using

const tasks = require('./tasks.json')

However, when I run tsc, the output directory does not contain no tasks.json file, causing a runtime error.

Is there a way to tell the compiler that it should copy all json files, or should I manually copy/paste all my json files into the dist directory ?

my tsc compilerOptions currently reads

  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "sourceMap": true,
    "noImplicitAny": true,
    "removeComments": false,
    "outDir": "./dist/",
    "sourceMap": true,
    "pretty": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "sourceMap": true
  },

Thanks !

解决方案

Problem

For people wanting to copy all JSON files, it's really difficult in TypeScript. Even with "resolveJsonModule": true, tsc will only copy .json files which are directly referenced by an import.

Here is some example code that wants to do a dynamic runtime require(). This can only work if all the JSON files have been copied into the dist/ folder, which tsc refuses to do.

// Works
import * as config from './config.default.json';

const env = process.env.NODE_ENV || 'development';

const envConfigFile = `./config.${env}.json`;

if (fs.existsSync(envConfigFile)) {
  // Does not work
  const envConfig = require(envConfigFile);
  Object.assign(config, envConfig);
}

Solution 1: Keep json files outside the src tree (recommended)

Assuming you have /src/ and /dist/ folders, you could keep your JSON files in the project's / folder. Then a script located at /src/config/load-config.ts could do this at runtime:

const envConfig = require(`../../config.${env}.json`);

// Or you could read manually without using require
const envConfigFile = path.join(__dirname, '..', '..', `config.${env}.json`);
const envConfig = JSON.parse(fs.readFileSync(envConfigFile, 'utf-8'));

This is the simplest solution. You just need to make sure the necessary config files will be in place in the production environment.

The remaining solutions will deal with the case when you really want to keep the config files in your src/ folder, and have them appear in your dist/ folder.

Solution 2: Import all possible files

For the above example we could do:

import * as config from './config.default.json';
import * as testingConfig from './config.testing.json';
import * as stagingConfig from './config.staging.json';
import * as productionConfig from './config.production.json';

This should cause the specified json files to be copied into the dist/ folder, so our require() should now work.

Disadvantage: If someone wants to add a new .json file, then they must also add a new import line.

Solution 3: Copy json files separately (recommended)

You can add a cpy-cli or copyfiles step to your build process to copy all .json files into the dist/ folder, after tsc has finished.

This assumes you do your builds with npm run build or something similar.

For example:

$ npm install --save-dev cpy-cli

// To copy just the json files, add this to package.json
"postbuild": "cpy --cwd=src --parents '**/*.json' ../dist/",

// Or to copy everything except TypeScript files
"postbuild": "cpy --cwd=src --parents '**/*' '!**/*.ts' ../dist/",

Now npm run build should run tsc, and afterwards run cpy.

Disadvantages: It requires an extra devDependency. And you must make this part of your build process.

Solution 4: Use js files instead of json files

Alternatively, don't use .json files. Move them into .js files instead, and enable "allowJs": true in your tsconfig.json. Then tsc will copy the files over for you.

Your new .js files will need to look like this: module.exports = { ... };

I found this idea recommended here.

Note: In order to enable "allowJs": true you might also need to add "esModuleInterop": true and "declaration": false, and maybe even "skipLibCheck": true. It depends on your existing setup.

And there is one other concern (sorry I didn't test this):

  • Will tsc transpile your config files if they are not all statically referenced by other files? Your files or their folders may need to be referenced explicitly in the files or include options of your tsconfig.json.

Solution 5: Use ts files instead of json files

Sounds easy, but there are still some concerns to consider:

  • Your config files will now look something like this: const config = { ... }; export default config;

  • See the note above about files / include options.

  • If you load the config files dynamically at runtime, don't forget they will have been transpiled into .js files. So don't go trying to require() .ts files because they won't be there!

  • If someone wants to change a config file, they should do a whole new tsc build. They could hack around with transpiled .js files in the dist folder, but this should be avoided because the changes may be overwritten by a future build.

Testing

When experimenting with this, please be sure to clear your dist/ folder and tsconfig.tsbuildinfo file between builds, in order to properly test the process.

(tsc does not always clean the dist/ folder, sometimes it just adds new files to it. So if you don't remove them, old files left over from earlier experiments may produce misleading results!)

这篇关于告诉打字稿编译json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆