【发布时间】:2021-09-14 22:09:29
【问题描述】:
我是打字稿新手。我不知道如何在脚本中引用(导入)模块
在我引用的index.html 文件中
<script src="main.js"></script>
在main.ts 文件中,我正在尝试导入另一个类型脚本模块
import greet from './greeter';
greet();
在greeter.ts 文件中我正在导出一个函数
export default function greet(): void {
console.log('Hello World');
}
但是在浏览器控制台中我看到一个错误,上面写着Uncaught ReferenceError: exports is not defined
这是我的tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
我尝试将"module" 属性更改为"es2015",但它不起作用。
【问题讨论】:
-
我认为你必须先编译它。浏览器(如果我错了,请纠正我)不能使用打字稿。
-
我转译了它。如果你仔细观察,你会发现我在我的 html 文件中链接了转译的
js文件 -
您是否尝试将脚本类型设置为模块?
type="module":developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…见最后一节:“还有一点值得注意:”&stackoverflow.com/a/44591205/5781499 -
我不知道!如果您指定
type="module",它确实有效。但是您通过npm或yarn安装的任何软件包都无法导入。它在浏览器控制台中显示Failed to resolve module specifier "<package-name>". Relative references must start with either "/", "./", or "../".
标签: javascript html typescript module script-tag