JavaScript-如何使ES6导入在浏览器中工作? [英] JavaScript - How to make ES6 imports work in browser?

查看:117
本文介绍了JavaScript-如何使ES6导入在浏览器中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting a new project in which I'd like to have ES6 style modules, however, I can't get it to run in a browser. I'm using Chrome.

我将问题分成几行代码.

I isolated the issue into very few lines of code.

这是我的2个TypeScript文件:

Here are my 2 TypeScript files:

app.ts

import { Component } from './component';

var component: Component = new Component();

component.ts

export class Component {

}

这是它们如何编译为JavaScript:

Here's how they compile to JavaScript:

app.js

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

component.js

export class Component {
}

我的index.html仅包含一个脚本标记.我尝试了一些变体,但没有一个起作用.

My index.html only contains a script tag. I tried a few variations, but none of them worked.

index.html#1

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

脚本未加载. (网络"标签中没有请求)

The script is not loaded. (No request in network tab)

index.html#2

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

脚本未加载. (网络"标签中没有请求)

The script is not loaded. (No request in network tab)

index.html#3

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

未捕获的SyntaxError:意外令牌{

Uncaught SyntaxError: Unexpected token {

我正在使用tsc通过Visual Studio Code转换TypeScript.

I'm using tsc to transpile TypeScript via Visual Studio Code.

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在服务器端和客户端应用程序中广泛使用,这有助于开发人员之间已经存在的困惑

To be honest - I think this is a good question because JS is widely use in both server-side and client-side application, which contributes to the already existing confusion among developers

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

It's clear that your TS code is written as server-side code (probably on Node.js). Trying to run it (as is) on client-side is... well.. tricky. The reason: The syntax you are using in your code suppose to run on server-side (not on client-side). Is there a workaround? Well... yes!

好消息:

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

JS ES6 does have a native module loader! (check MDN)

坏人:

  • 语法与Node.js模块加载器语法(导出模块时)不同
  • 仅部分支持(仅适用于现代浏览器)
  • Syntax is different from Node.js module loader syntax (when exporting a module)
  • Support is very partial (modern browsers only)

一些附加说明:

  • 模块加载的常见语法与名为require js的第三方库相关联( https://requirejs.org/).您可以在客户端项目中使用此库,但必须安装并正确配置它(文档对此非常清楚)
  • 您始终可以使用任务运行程序,例如grunt( https://gruntjs.com/)或类似项目帮助您将所有代码最小化并统一到生产环境中的单个文件中.你为什么问?当客户端访问您的网站时,它将明显地帮助您减轻负载(就网络流量而言,文件越少越好)
  • The common syntax of modules loading is associated with a third-party library called require js (https://requirejs.org/). You can use this library in client side projects but you have to install it and configure it properly (the docs are pretty clear about how to do that)
  • You can always use a task runner like grunt (https://gruntjs.com/) or similar projects to assist you to minify and unify all your code to a single file in production. Why you ask? It will clearly help you ease the load when a client fetch you website (less files are better in terms of network traffic)

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

As you see, there is no quick or simple answer to your question.. but it may be a good starting point to improve your knowledge and building better modern web apps.

UPDATE

UPDATE

根据要求,我创建了一个小沙盒演示,演示了如何使用ES6本机模块( https://codesandbox .io/s/oj2rwm9v35 )

As requested, I created a little sandbox demo that shows how to use ES6 native module (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!";
}

这篇关于JavaScript-如何使ES6导入在浏览器中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆