HTML引入Typescript编译JS文件 :Uncaught ReferenceError: exports is not defined

初学TypeScript,尝试在html引入ts编译出来的js文件:

报错:Uncaught ReferenceError: exports is not defined

以下是代码:

创建了TS:加入export {}形成独立的作用域,其他ts文件重复声明相同名称的变量。

export {}
let str = "tt";
// str=22 //类型不对,编辑器IDE会提示错误

let a:string="44"
console.log(str)

tsconfig.json配置:

/* Modules */
"module": "commonjs",    

编译之后生成js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let str = "tt";
// str=22 //类型不对,编辑器IDE会提示错误
let a = "44";
console.log(str);

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="01-基础.js"></script>
</head>
<body>

</body>
</html>

运行时报错:Uncaught ReferenceError: exports is not defined。

解决步骤:

  说是要配置生成ESXX,我把生成模块类型改成ES2020版本了。

tsconfig.json配置:

/* Modules */
"module": "ES2020", 

再次运行报错:

Uncaught SyntaxError: export declarations may only appear at top level of a module

引入类型设置为module

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="module" src="01-基础.js"></script>
</head>
<body>

</body>
</html>

再次运行OK:

猜你喜欢

转载自blog.csdn.net/LlanyW/article/details/130200343