Javascript 在TypeScript中使用ES2015模块而不使用模块加载器
我有一个我想配置的TypeScript项目,因此它使用ES2015模块,而不使用任何模块绑定器,如Browserify或Webpack ,有一个选项指定生成哪种类型的模块,例如CommonJS、AMD、ES2015等。我的选项设置为ES2015 我遇到的问题是,呈现的JavaScript使用“/file”语法而不是“/file.js”语法导入模块。浏览器中的JavaScript模块必须以.js结尾,否则将生成404 not found错误 我发现唯一有效的解决方案是在TypeScript文件本身中指定“/file.js”语法,这是不正确的 我可以做些什么来获取在呈现的JavaScript文件中导入的模块的.js文件扩展名 index.htmlJavascript 在TypeScript中使用ES2015模块而不使用模块加载器,javascript,html,node.js,typescript,npm,Javascript,Html,Node.js,Typescript,Npm,我有一个我想配置的TypeScript项目,因此它使用ES2015模块,而不使用任何模块绑定器,如Browserify或Webpack ,有一个选项指定生成哪种类型的模块,例如CommonJS、AMD、ES2015等。我的选项设置为ES2015 我遇到的问题是,呈现的JavaScript使用“/file”语法而不是“/file.js”语法导入模块。浏览器中的JavaScript模块必须以.js结尾,否则将生成404 not found错误 我发现唯一有效的解决方案是在TypeScript文件本身
<!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>
动物实验
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.`);
}
}
狗狗
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文件中导入的模块的.js文件扩展名
不多,看。您可以编写自己的转换,并使用类似的东西来代替常规编译器
我发现唯一有效的解决方案是在TypeScript文件本身中指定“/file.js”语法,这是不正确的
不,这没有错,这是TypeScript团队的一些成员和。从某种意义上讲,TypeScript仍然会查找并编译.ts
文件(如果存在),而不是.js
文件
另见
另一个可能的解决方案是使用无扩展导入并将其映射到浏览器中的URL。然而,它仍然是“规范进行中”并且是
{
"compilerOptions": {
"module": "ES2015",
"outDir": "js",
"sourceMap": true,
"strict": true,
"target": "es2017"
},
"exclude": [
"node_modules"
]
}