typescript 告诉打字稿编译json文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40471152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
tell typescript to compile json files
提问by aherve
The typescript compiler works fine when I import a json file using
当我使用导入 json 文件时,打字稿编译器工作正常
const tasks = require('./tasks.json')
However, when I run tsc
, the output directory does not contain no tasks.json
file, causing a runtime error.
但是,当我运行时tsc
,输出目录不包含任何tasks.json
文件,从而导致运行时错误。
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 ?
有没有办法告诉编译器它应该复制所有 json 文件,还是应该手动将所有 json 文件复制/粘贴到dist
目录中?
my tsc compilerOptions currently reads
我的 tsc compilerOptions 当前读取
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"noImplicitAny": true,
"removeComments": false,
"outDir": "./dist/",
"sourceMap": true,
"pretty": true,
"noImplicitThis": true,
"strictNullChecks": true,
"sourceMap": true
},
Thanks !
谢谢 !
回答by F?rat Kü?üK
In typescript 2.9+ you can use JSON files directly and it automatically copied to dist directories.
在 typescript 2.9+ 中,您可以直接使用 JSON 文件,它会自动复制到 dist 目录。
This is tsconfig.json
with minimum needed configuration:
这是tsconfig.json
所需的最低配置:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop" : true,
"module" : "commonjs",
"outDir" : "./dist",
"resolveJsonModule" : true,
"target" : "es6"
},
"exclude" : [
"node_modules"
]
}
Then you can create a json file.
然后你可以创建一个json文件。
{
"address": "127.0.0.1",
"port" : 8080
}
Sample usage:
示例用法:
import config from './config.json';
class Main {
public someMethod(): void {
console.log(config.port);
}
}
new Main().someMethod();
If you don't use esModuleInterop
property you should access your json properties encapsulated in default field. config.default.port
.
如果您不使用esModuleInterop
属性,则应访问封装在默认字段中的 json 属性。config.default.port
.
回答by JerinDJoy
In tsconfig.json, add
在 tsconfig.json 中,添加
{
"compilerOptions": {
"resolveJsonModule": true,
},
"include": [
"src/config/*.json"
]
}
Notice that it won'tcopy those json
files which are require
d. If you need to dynamically require some json
files and need them to be copied to dist
, then you need to change from, for example,
请注意,它不会复制那些d 的json
文件require
。如果您需要动态地要求某些json
文件并需要将它们复制到dist
,那么您需要从,例如,
return require("some.json") as YourType
to
到
return (await import("some.json")) as YourType
.
.
回答by joeytwiddle
Problem
问题
For people wanting to copy allJSON files, it's really difficult in TypeScript. Even with "resolveJsonModule": true
, tsc
will only copy .json
files which are directly referencedby an import
.
对于想要复制所有JSON 文件的人来说,在 TypeScript 中真的很难。即使有"resolveJsonModule": true
,tsc
只会复制.json
这些文件直接引用的一个import
。
Here is some example code that wants to do a dynamicruntime require()
. This can only work if all the JSON files have been copied the dist/
folder, which tsc
refusesto do.
下面是一些想要执行动态运行时的示例代码require()
。这只有在所有 JSON 文件都已复制到dist/
文件夹时才有效,而tsc
拒绝这样做。
// Works
import * as config from './config.default.json';
const localConfigFile = `./config.${process.env.NODE_ENV || 'development'}.json`;
if (fs.existsSync(localConfigFile)) {
// Does not work
const envConfig = require(localConfigFile);
Object.assign(config, envConfig);
}
Solution 0: Import all possible files
解决方案 0:导入所有可能的文件
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.
这应该会导致指定的 json 文件被复制到dist/
文件夹中,所以我们require()
现在应该可以工作了。
Disadvantage: If someone wants to add a new .json
file, then they must also add a new import line.
缺点:如果有人要添加一个新.json
文件,那么他们还必须添加一个新的导入行。
Solution 1: Copy json files separately
方案一:单独复制json文件
You can add a cpy-cli
or copyfiles
step to your build processto copy all .json
files into the dist/
folder, after tsc
has finished.
完成后,您可以在构建过程中添加cpy-cli
或copyfiles
步骤以将所有.json
文件复制到dist/
文件夹tsc
中。
This assumes you do your builds with npm run build
or something similar.
这假设您使用npm run build
或类似的东西进行构建。
It also requires an extra devDependency. But it does achieve the original goal of copying all the .json
files into the dist/
folder.
它还需要额外的 devDependency。但它确实实现了将所有.json
文件复制到文件dist/
夹中的原始目标。
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
.
现在npm run build
应该运行tsc
,然后运行cpy
。
Solution 2: Use js files instead of json files
解决方案2:使用js文件代替json文件
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.
或者,不要使用.json
文件。.js
改为将它们移动到文件中,并"allowJs": true
在您的tsconfig.json
. 然后tsc
将为您复制文件。
Your new .js
files will need to look like this: module.exports = { ... };
您的新.js
文件需要如下所示:module.exports = { ... };
I found this idea recommended here.
我发现这里推荐的这个想法。
Note: In order to enable
"allowJs": true
you might alsoneed to add"esModuleInterop": true
and"declaration": false
, and maybe even"skipLibCheck": true
. It depends on your existing setup.
注意:为了启用
"allowJs": true
您可能还需要添加"esModuleInterop": true
和"declaration": false
,甚至可能需要添加"skipLibCheck": true
。这取决于您现有的设置。
And there is one other concern:
还有一个问题:
- 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 thefiles
orinclude
options of yourtsconfig.json
.
tsc
如果您的配置文件不是全部被其他文件静态引用,是否会转译您的配置文件?您的文件或文件夹,它们可能需要将在明确提到files
或include
您的选择tsconfig.json
。
Solution 3: Use ts files instead of json files
解决方案 3:使用 ts 文件而不是 json 文件
Sounds easy, but there are still some concerns to consider:
听起来很简单,但仍有一些问题需要考虑:
Your config files will look (something) like this:
const config = { ... }; export default config;
or maybe lots of small exports. See what works ;-)See the note above about
tsconfig.json
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 torequire()
.ts
files because they won't be there!If someone wants to change a config file, they will either need to do a whole new
tsc
build, or they will need to hack around with transpiled.js
files in thedist
folder. This is probably the least intuitive part of this approach.
你的配置文件看起来(有点)像这样:
const config = { ... }; export default config;
或者可能有很多小的导出。看看什么有效;-)请参阅上面的注释
tsconfig.json
如果您在运行时动态加载配置文件,请不要忘记它们将被转换为
.js
文件。所以不要去尝试require()
.ts
文件,因为它们不会在那里!如果有人想要更改配置文件,他们要么需要进行全新的
tsc
构建,要么需要使用.js
文件dist
夹中的转译文件进行破解。这可能是这种方法中最不直观的部分。
Testing
测试
When experimenting with this, please be sure to clearyour dist/
folder and tsconfig.tsbuildinfo
between builds, in order to properly test the process. (tsc
does not clean the dist/
folder, it only adds new files to it, so old files left over from earlier builds may produce misleading results.)
在尝试此操作时,请务必清除您的dist/
文件夹以及tsconfig.tsbuildinfo
构建之间的文件夹,以便正确测试该过程。(tsc
不会清理dist/
文件夹,只会向其中添加新文件,因此早期版本遗留的旧文件可能会产生误导性结果。)
回答by Aaron Beall
The typescript compiler works fine when I import a json file using
const tasks = require('./tasks.json')
当我使用导入 json 文件时,打字稿编译器工作正常
const tasks = require('./tasks.json')
TypeScript wouldn't complain about this as long as you have a global require()
function defined, for example using node.d.ts
. With a vanilla setup you would actually get a compile error that require
is not defined.
只要您require()
定义了一个全局函数,例如使用node.d.ts
. 使用 vanilla 设置,您实际上会得到一个require
未定义的编译错误。
Even if you've told TypeScript about a global require
function it just sees it as a function that's expected to return something, it doesn't make the compiler actually analyze what the function is requiring ("tasks.json"
) and do anything with that file. This is the job of a tool like Browserifyor Webpack, which can parse your code base for require
statements and load just about anything (JS, CSS, JSON, images, etc) into runtime bundles for distribution.
即使你已经告诉 TypeScript 一个全局require
函数,它只是将它视为一个预期会返回一些东西的函数,它不会让编译器实际分析函数需要什么 ( "tasks.json"
) 并对该文件执行任何操作。这是像Browserify或Webpack这样的工具的工作,它可以解析require
语句的代码库,并将几乎任何东西(JS、CSS、JSON、图像等)加载到运行时包中进行分发。
Taking this a little further, with TypeScript 2.0 you can even tell the TypeScript Compiler about module path patterns that will be resolved and loaded by a bundler (Browserify or Webpack) using wildcard (*
) module name declarations:
更进一步,使用 TypeScript 2.0,您甚至可以告诉 TypeScript 编译器有关模块路径模式的信息,这些模式将由捆绑程序(Browserify 或 Webpack)使用通配符 ( *
) 模块名称声明解析和加载:
declare module "*.json" {
const value: any;
export default value;
}
Now you can import your JSON in TypeScript using ES6 module syntax:
现在您可以使用 ES6 模块语法在 TypeScript 中导入您的 JSON:
import tasks from "./tasks.json";
Which will not give any compile error and will transpile down to something like var tasks = require("./tasks.json")
, and your bundler will be responsible for parsing out the require
statements and building your bundle including the JSON contents.
这不会给出任何编译错误,并且会转译为类似的内容var tasks = require("./tasks.json")
,并且您的打包器将负责解析require
语句并构建您的包,包括 JSON 内容。
回答by Besufkad Menji
you can include this into your build script && ncp src/res build/res
, will copy the files directly to your outDir
您可以将其包含在您的构建脚本中&& ncp src/res build/res
,将文件直接复制到您的 outDir