我正在开始一个新的项目,其中我希望有ES6样式的模块,但是,我不能让它在浏览器中运行。我用的是Chrome。
我将问题分解为很少的几行代码。
下面是我的两个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"
]
}
发布于 2018-10-28 02:16:24
老实说-我认为这是一个很好的问题,因为JS
在服务器端和客户端应用程序中都被广泛使用,这导致了开发人员之间已经存在的困惑
很明显,您的TS
代码是作为服务器端代码(可能是在Node.js
上)编写的。尝试(按原样)在客户端运行它是...好吧..。很棘手。原因:您在代码中使用的语法应该运行在服务器端(而不是客户端)。有解决办法吗?好吧..。是!
好消息:
JS ES6
有一个本机模块加载器!(check MDN)
不好的:
Node.js
模块加载器语法不同(导出时非常不完整(仅限现代浏览器)一些补充说明:
如您所见,您的问题没有快速或简单的答案。但这可能是提高你的知识和构建更好的现代web应用程序的一个很好的起点。
更新
按照要求,我创建了一个演示如何使用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!";
}
https://stackoverflow.com/questions/53023279
复制相似问题