【发布时间】:2019-11-06 19:27:06
【问题描述】:
我有一个我想配置的 TypeScript 项目,因此它使用 ES2015 模块,而没有任何模块捆绑器,例如 Browserify 或 Webpack。
In the TypeScript compiler documentation,有一个选项可以指定生成哪种类型的模块,例如CommonJS、AMD、ES2015 等。我的选项设置为 ES2015。
我遇到的问题是渲染的 JavaScript 使用“./file”语法而不是“./file.js”语法导入模块。浏览器中的 JavaScript 模块必须以 .js 结尾,否则会产生 404 not found 错误。
我发现唯一可行的解决方案是在 TypeScript 文件本身中指定“./file.js”语法,这是不正确的。
我可以做些什么来为在渲染的 JavaScript 文件中导入的模块获取 .js 文件扩展名?
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo</title>
<base href="/">
</head>
<body>
<script type="module" src="./js/index.js"></script>
</body>
</html>
index.ts
import { Cat } from './cat'
import { Dog } from './dog'
let cat = new Cat('Lily');
cat.eat();
cat.sleep();
cat.meow();
let dog = new Dog('Rex');
dog.eat();
dog.sleep();
dog.bark();
动物.ts
export class Animal {
public readonly name: string;
public constructor(
name: string
) {
this.name = name;
}
public sleep(): void {
console.log(`${this.name} is sleeping.`);
}
public eat(): void {
console.log(`${this.name} is eating.`);
}
}
cat.ts
import { Animal } from './animal'
export class Cat extends Animal {
public meow(): void {
console.log(`${this.name} is meowing.`);
}
}
dog.ts
import { Animal } from './animal'
export class Dog extends Animal {
public bark(): void {
console.log(`${this.name} is barking.`);
}
}
package.json
{
"scripts": {
"start": "http-server -a localhost -p 5000 -c-1"
},
"devDependencies": {
"http-server": "^0.9.0",
"ts-loader": "^6.0.4",
"typescript": "^3.5.2"
}
}
tsconfig.json
{
"compilerOptions": {
"module": "ES2015",
"outDir": "js",
"sourceMap": true,
"strict": true,
"target": "es2017"
},
"exclude": [
"node_modules"
]
}
【问题讨论】:
标签: javascript html node.js typescript npm