【问题标题】:Using ES2015 Modules In TypeScript Without A Module Loader在没有模块加载器的情况下在 TypeScript 中使用 ES2015 模块
【发布时间】: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


    【解决方案1】:

    我可以做些什么来为在渲染的 JavaScript 文件中导入的模块获取 .js 文件扩展名?

    不多,见this github issue。您可以编写自己的转换并使用 ttypescript 之类的东西来代替常规编译器。

    我发现唯一可行的解​​决方案是在 TypeScript 文件本身中指定“./file.js”语法,这是不正确的。

    不,这不是错误的,这是 TypeScript 团队的一些成员 had recommendedsome people are actually using。它有效,因为 TypeScript 仍然会查找并编译 .ts 文件(如果存在),而不是 .js 文件。

    另见this issue

    另一个潜在的解决方案是使用import mapsimport map generator 将无扩展名导入映射到浏览器中的URL。但是,它仍然是“规范中”并且是not yet implemented in all browsers

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 2019-03-21
      • 2018-10-14
      • 2015-01-13
      • 2016-05-01
      • 2015-12-17
      • 2022-11-04
      • 1970-01-01
      • 2019-09-26
      相关资源
      最近更新 更多