【发布时间】:2020-04-28 11:30:17
【问题描述】:
我正在寻找一个使用typescript 创建的网络应用程序的小示例。我在导入模块时遇到问题。
我只想了解为什么这是错误的以及我必须对它进行排序的选项。
问题是在尝试导入 hello 时 index.js 文件中的 404。
代码如下:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>Check the console log...</p>
</body>
<script type="module" src="/dist/index.js"></script>
</html>
index.ts
import { HelloWorld } from "./hello";
var helloWorld = new HelloWorld();
helloWorld.sayHello();
你好.ts
export class HelloWorld {
constructor() {
}
sayHello() {
console.log("Hello, world!");
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"lib": ["es2015", "dom"],
"moduleResolution": "node",
"allowJs": true,
"checkJs": true,
"sourceMap": true,
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true
}
}
上面使用tsc编译app的输出如下:
dist
hello.js
hello.js.map
index.js
index.js.map
如下:
你好.js
export class HelloWorld {
constructor() {
}
sayHello() {
console.log("Hello, world!");
}
}
//# sourceMappingURL=hello.js.map
index.js
import { HelloWorld } from "./hello";
var helloWorld = new HelloWorld();
helloWorld.sayHello();
//# sourceMappingURL=index.js.map
现在,如果我将 index.ts 更改为完整的 hello.js 而不是 hello,那么这将起作用。这感觉不对 - 因为在我编写此代码时没有 index.js。
在ES2015 兼容的浏览器(如 Chrome)中运行解决此问题的正确方法是什么?
我必须使用诸如requirejs 之类的东西吗?
【问题讨论】: