gpt4 book ai didi

javascript - 如何立即从 html 使用 WebStorm 中生成的 TypeScript?

转载 作者:行者123 更新时间:2023-12-01 01:03:13 32 4
gpt4 key购买 nike

我已经尝试了所有答案,但我遇到了诸如此类的错误

main.js:2 Uncaught ReferenceError: exports is not defined

当我使用编译到 es5 作为目标时

Uncaught SyntaxError: Unexpected token {

当我使用编译到 es6 作为目标时

main.ts

import {MyLib} from './mylib';
let myLib = new MyLib("Anonymous", "Someone");
console.warn(myLib);

mylib.ts

export class MyLib {
constructor(public a: String, public b: String) {

}


toString() {
return "library tostring: " + this.a + " " + this.b;
}
}

tsconfig.json

{
"compilerOptions": {
"target": "es6",
"sourceMap": true
},
"exclude": [
"node_modules"
]
}

index.html

<html>

<head>
<title>
ts-demo !!
</title>

<script type="module" src="./require.js"></script>
<script type="module" src="./system.min.js"></script>

<script src="./tsdemo/main.js"></script>
</head>
<body>

</body>

</html>

最佳答案

  1. 您需要设置 <script>输入 module让 ES6 模块正常工作,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="module" src="./tsdemo/main.js"></script>
</head>
<body>
</body>
</html>
  • 此外,.js导入时需要扩展名才能使其在浏览器中工作。 Typescript 编译器没有自动添加它的选项( https://github.com/Microsoft/TypeScript/issues/16577 ),但您可以在 main.ts 中添加扩展名文件,例如:
  •     import {MyLib} from './mylib.js';
    let myLib = new MyLib("Anonymous", "Someone");

    console.warn(myLib);

    tsc 做了正确的事情并解析 .ts 中的类型文件,在生成的 javascript 中保留扩展名

    关于javascript - 如何立即从 html 使用 WebStorm 中生成的 TypeScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870008/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com