客户端中的Typescript模块-最好的方法是什么?

我正在构建一个Web应用程序。 我在客户端使用打字稿,在服务器端使用golang。 我使用打字稿3.9.2。

I want to compile the .ts files to .js, and use modules. The default compiling compile it to CommonJS module loader. Then in the browser it has some exports.__... in the second line. I searched and it basicly said it want a variable called exports, which I don't have. In this case, I don't like the main solution to define a mock exports in other script tag.

I changed the compilerOption to "module":"ES6" and then it compile and loaded well (after changing the type of the script to module), but the browser can't find the module i want to import.

代码如下:

use.ts

import * as fun from 'funcs'
let bar =  fun.foo()

funcs.ts

export function foo() :boolean{
return true;
}

use.js

import * as fun from 'funcs'
var bar =  fun.foo()

funcs.js

export function foo(){
return true;
}

And now the browser can't find /funcs, which it needs for the use.js. When i change manualy the first line in use.js to

import * as fun from 'funcs.js'

有用。

我怎样做才能使一切自动化? 最佳做法是什么?

评论
琴和雅
琴和雅

ES Module imports need to have the .js extension, but Typescript's modules don't and right now there does not appear to be a built-in option to add them automatically, but somebody did write a script to add the extensions to the imports, or you can add them to the imports manually.

There is some discussion on the TypeScript Github about this and related issues. They are considering adding a module resolution option to the compiler for the browser.

点赞
评论