简体   繁体   English

打字稿知道导入->必需,但不知道必需->导入?

[英]Typescript knows import -> require but doesn't know require -> import?

I have a simple file which is using es6 module loader : 我有一个使用es6模块加载器的简单文件:

1.ts 1.ts

import {foo} from "./2"
foo('hello');

2.ts 2.ts

function foo (a){console.log(a);};
export {foo}

When tsconfig is set to : tsconfig设置为时:

"module": "commonjs",

We can see that it converts import to require : 我们可以看到它将import转换为require

(output)1.js (输出)1.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _2_1 = require("./2");
_2_1.foo('hello');

That's fine. 没关系。 But if I now use module loading via require : 但是如果我现在通过require使用模块加载:

1.ts 1.ts

var a = require("./2")
a('hello');

2.ts 2.ts

function foo (a){console.log(a);};
module.exports.foo= foo 

And set "module": "es6", : then the output is : 并设置"module": "es6",然后输出为:

(output)1.js (输出)1.js

var a = require("./2");  // why it didnt compile it to `import` ??
a('hello');

Question: 题:

What is the reason that TS can't compile require to import ? TS无法编译require import的原因是什么?

TypeScript normalised their syntax on the ECMAScript version of the import syntax. TypeScript在导入语法的ECMAScript版本上将其语法标准化。 All of your TypeScript code should use this style: 您所有的TypeScript代码都应使用以下样式:

import { ZipCodeValidator } from "./ZipCodeValidator";

The compiler will happily convert this into the AMD, CommonJS, or System style of imports - but it doesn't unidirectionally map from each of these to each other one of these. 编译器会很乐意将其转换为AMD,CommonJS或System风格的导入-但它不会单向地将它们相互映射。

So the short version is, write ECMAScript imports and use the compiler flag to have them converted into whatever you like. 因此,简短的版本是编写ECMAScript导入,并使用编译器标志将其转换为所需的格式。

As an aside, when actually intending to use the ECMAScript module loader, adding .js works within the import statement - ie TypeScript understands what you mean. 顺便说.js ,当实际打算使用ECMAScript模块加载器时,在import语句中添加.js是可行的-即TypeScript理解您的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM