[英]Typescript modules in client side - What is the best way?
I am building a web application.我正在构建一个 web 应用程序。 I use typescript for the client side and golang for the server side.我在客户端使用 typescript,在服务器端使用 golang。 I use typescript 3.9.2.我使用 typescript 3.9.2。
I want to compile the .ts
files to .js
, and use modules.我想将.ts
文件编译为.js
,并使用模块。 The default compiling compile it to CommonJS module loader.默认编译将其编译为CommonJS模块加载器。 Then in the browser it has some exports.__...
in the second line.然后在浏览器中它有一些exports.__...
在第二行。 I searched and it basicly said it want a variable called exports, which I don't have.我搜索了一下,它基本上说它想要一个名为 exports 的变量,但我没有。 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.我将compilerOption
更改为"module":"ES6"
然后它编译并加载良好(在将脚本类型更改为模块之后),但浏览器找不到我要导入的模块。
The code goes like this:代码是这样的:
use.ts使用.ts
import * as fun from 'funcs'
let bar = fun.foo()
funcs.ts函数.ts
export function foo() :boolean{
return true;
}
use.js使用.js
import * as fun from 'funcs'
var bar = fun.foo()
funcs.js函数.js
export function foo(){
return true;
}
And now the browser can't find /funcs
, which it needs for the use.js
.现在浏览器找不到 use.js 需要的/funcs
use.js
。 When i change manualy the first line in use.js
to当我手动将use.js
中的第一行更改为
import * as fun from 'funcs.js'
It works.有用。
What can i do to make everything automatic?我该怎么做才能使一切自动化? What is the best practice here?这里的最佳做法是什么?
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. ES 模块导入需要有.js
扩展名,但 Typescript 的模块不需要,现在似乎没有自动添加它们的内置选项,但有人写了一个脚本来将扩展名添加到导入中,或者您可以手动将它们添加到导入中。
There is some discussion on the TypeScript Github about this and related issues. TypeScript Github 上有一些关于这个和相关问题的讨论。 They are considering adding a module resolution option to the compiler for the browser.他们正在考虑为浏览器的编译器添加一个模块解析选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.