JavaScript - How to make ES6 imports work in browser?

断了今生、忘了曾经 提交于 2020-01-11 06:07:26

问题


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.

Here are my 2 TypeScript files:

app.ts

import { Component } from './component';

var component: Component = new Component();

component.ts

export class Component {

}

Here's how they compile to JavaScript:

app.js

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

component.js

export class Component {
}

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>

Uncaught SyntaxError: Unexpected token {

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"
  ]
}

回答1:


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

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!

The good news:

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

The bad ones:

  • Syntax is different from Node.js module loader syntax (when exporting a module)
  • Support is very partial (modern browsers only)

Some additional notes:

  • 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 tadk runner like grunt 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)

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

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!";
}


来源:https://stackoverflow.com/questions/53023279/javascript-how-to-make-es6-imports-work-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!