我正在开始一个新项目,在该项目中我想拥有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"
]
}
答案 0 :(得分:2)
说实话-我认为这是一个好问题,因为JS
已在服务器端和客户端应用程序中广泛使用,这加剧了开发人员之间已经存在的困惑
很明显,您的TS
代码是作为服务器端代码编写的(可能在Node.js
上)。尝试(按原样)在客户端运行它是..棘手的。原因:您在代码中使用的语法假设是在服务器端(而不是客户端)上运行。有解决方法吗?嗯...是的!
好消息:
JS ES6
确实具有本机模块加载器! (check MDN)
坏人:
Node.js
模块加载程序语法(导出模块时)不同一些其他说明:
如您所见,您的问题没有快速或简单的答案..但这可能是提高您的知识并构建更好的现代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!";
}