【发布时间】:2019-04-01 01:45:31
【问题描述】:
我正在开始一个新项目,我希望在其中拥有 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>
Uncaught SyntaxError: Unexpected token {
我正在使用 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"
]
}
【问题讨论】:
-
很简单:他们没有
-
你确定吗?如果是这样,我在这里误解了什么? contentful.com/blog/2017/04/04/…
-
是的,您可以直接在最新的浏览器中使用模块,无需打包器!您应该在不定义任何特定模块系统的情况下将 ts 转换为 js 文件。然后你可以在浏览器中加载模块
<script type=‘module’ src=‘thing.js’> -
好的,我现在正在做,js 看起来更干净了,但是脚本仍然没有加载。我在原始问题的底部添加了更多信息。
-
你试过写一个最小的构造函数吗? TS classes
标签: javascript ecmascript-6 es6-modules es6-module-loader