简体   繁体   中英

Typescript modules in client side - What is the best way?

I am building a web application. I use typescript for the client side and golang for the server side. I use typescript 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.

The code goes like this:

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'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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