JavaScript - 如何使 ES6 导入在浏览器中工作?

JavaScript - How to make ES6 imports work in browser?

我正在开始一个新项目,我想在其中使用 ES6 样式的模块,但是,我无法在浏览器中将其设置为 运行。我正在使用 Chrome.

我将问题分解为很少的几行代码。

这是我的 2 个 TypeScript 文件:

app.ts

import { Component } from './component';

var component: Component = new Component();

component.ts

export class Component {

}

下面是他们如何编译成 JavaScript:

app.js

import { Component } from './component';
var component = new Component();

component.js

export class Component {
}

我的index.html只包含一个脚本标签。我尝试了一些变体,但其中 none 有效。

index.html#1

<script src="src/app.js" type="module"></script>

脚本未加载。 (网络选项卡中没有请求)

index.html#2

<script src="src/app.js" type=module></script>

脚本未加载。 (网络选项卡中没有请求)

index.html#3

<script src="src/app.js"></script>

Uncaught SyntaxError: Unexpected token {

我正在使用 tsc 通过 Visual Studio 代码转译 TypeScript。

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "problemMatcher": [
                "$tsc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "reveal": "silent"
            }
        }
    ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "sourceMap": false,
    "removeComments": false,
    "noImplicitReturns": true,
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "outDir": "../src/"
  },
  "exclude": [
    "logs",
    "node_modules"
  ]
}

老实说 - 我认为这是一个很好的问题,因为 JS 在服务器端和客户端应用程序中都被广泛使用,这加剧了开发人员之间已经存在的混淆

很明显,您的 TS 代码是作为服务器端代码编写的(可能在 Node.js 上)。尝试在客户端 运行 它(按原样)是......嗯......棘手。原因:您在代码中使用的语法假定 运行 在服务器端(而不是在客户端)。有解决方法吗?嗯...是的!

好消息:

JS ES6 确实有一个本地模块加载器! (check MDN)

不好的:

  • 语法不同于 Node.js 模块加载器语法(导出模块时)
  • 支持非常部分(仅限现代浏览器)

一些补充说明:

  • 模块加载的常用语法与第三方库require js (https://requirejs.org/)相关联。您可以在客户端项目中使用此库,但您必须安装并正确配置它(文档非常清楚如何执行此操作)
  • 您始终可以使用诸如 g运行t (https://gruntjs.com/) 之类的任务 运行ner 或类似项目来帮助您将所有代码缩小并统一到一个文件中生产。你为什么问?当客户端获取您的网站时,它显然会帮助您减轻负载(就网络流量而言,文件越少越好)

如您所见,您的问题没有快速或简单的答案。但它可能是一个很好的起点,可以增进您的知识并构建更好的现代网络应用程序。

更新

应要求,我创建了一个小沙箱演示,展示了如何使用 ES6 原生模块 (https://codesandbox.io/s/oj2rwm9v35)

index.html

<html>
<body>
    <div id="app"></div>
    <script type="module" src="src/primary.js"></script>
</body>
</html>

primary.js

import test from "./test";

test();

test.js

export default function test() {
  document.querySelector("#app").textContent = "Hello JS module!";
}