据我所知,接口只与Typescript相关,tsc编译器应该足够智能,不会在最终输出中将它们转换为JS文件。当我编译我的代码时,接口就是用它编译的。为什么会这样呢?
我简化的项目结构
src/
index.ts
lib/
EventClient.ts
interfaces/
EventClientConfig.ts它编译成什么?
dist/
index.js
lib/
EventClient.js
interfaces/
EventClientConfig.js我的tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./dist",
"lib": ["ES6", "DOM"],
"target": "ES2018",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"baseUrl": ".",
"removeComments": true,
"strict": true,
"typeRoots": ["./node_modules/@types"],
"rootDir": "./src",
"types": [
"node",
"jest-fetch-mock",
"express",
"reflect-metadata"
]
},
"include": ["src"],
"exclude": ["dist", "node_modules", "**/*spec.ts"]
}一个接口
export interface EventClientConfig {
endpoint: string;
authToken: string;
}我如何使用这个接口
import { EventClientConfig } from '../interfaces/EventClientConfig';
const config: EventClientConfig = {
endpoint: '/api',
authToken: '123456'
}接口被编译成什么?
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });在编译后的代码中,EventClient.js并没有实际引用EventClientConfig.js,因此绝对不需要它。为什么Typescript要将接口文件编译成JS?
发布于 2020-05-08 22:57:47
你的问题的答案在这里modules
在TypeScript中,就像在ECMAScript 2015中一样,任何包含顶级导入或导出的文件都被视为模块。相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用(因此也可用于模块)的脚本。
发布于 2020-05-08 23:11:43
多亏了@AluanHaddad建议使用.d.ts声明文件,这个问题才得以解决。我已经更改了所有接口文件名,以便它们以.d.ts结尾,并且它们不再包含在输出中。
https://stackoverflow.com/questions/61681780
复制相似问题