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

时间:2018-10-27 15:10:15

标签: javascript ecmascript-6 es6-modules es6-module-loader

我正在开始一个新项目,在该项目中我想拥有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仅包含一个脚本标记。我尝试了一些变体,但没有一个起作用。

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>
  

未捕获的SyntaxError:意外令牌{

我正在使用tsc通过Visual Studio Code转换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"
  ]
}

1 个答案:

答案 0 :(得分:2)

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

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

好消息:

JS ES6确实具有本机模块加载器! (check MDN

坏人:

  • 语法与Node.js模块加载程序语法(导出模块时)不同
  • 仅部分支持(仅适用于现代浏览器)

一些其他说明:

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

如您所见,您的问题没有快速或简单的答案..但这可能是提高您的知识并构建更好的现代Web应用程序的一个很好的起点。

UPDATE

根据要求,我创建了一个小沙盒演示,演示了如何使用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!";
}