【问题标题】:How can I use TypeScript that was produced in WebStorm right away from html?如何立即使用在 WebStorm 中从 html 生成的 TypeScript?
【发布时间】:2019-04-26 14:44:27
【问题描述】:

我已经尝试了所有答案,但我遇到了类似的错误

main.js:2 未捕获的 ReferenceError:未定义导出

当我使用 compile to es5 作为目标时

Uncaught SyntaxError: Unexpected token {

当我使用 compile to es6 作为目标时

main.ts

import {MyLib} from './mylib';
let myLib = new MyLib("Anonymous", "Someone");
console.warn(myLib);

mylib.ts

export class MyLib {
    constructor(public a: String, public b: String) {

    }


    toString() {
        return "library tostring: " + this.a + " " + this.b;
    }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

index.html

<html>

    <head>
        <title>
            ts-demo !!
        </title>

        <script type="module" src="./require.js"></script>
        <script type="module" src="./system.min.js"></script>

        <script src="./tsdemo/main.js"></script>
    </head>
    <body>

    </body>

</html>

【问题讨论】:

    标签: javascript typescript requirejs phpstorm webstorm


    【解决方案1】:
    1. 您需要将&lt;script&gt; 类型设置为module 以使ES6 模块工作,例如:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="module" src="./tsdemo/main.js"></script>
    </head>
    <body>
    </body>
    </html>
    
    1. 另外,导入时需要.js 扩展名才能使其在浏览器中工作。 Typescript 编译器没有自动添加它的选项 (https://github.com/Microsoft/TypeScript/issues/16577),但您可以在 main.ts 文件中添加扩展名,例如:
        import {MyLib} from './mylib.js';
        let myLib = new MyLib("Anonymous", "Someone");
    
        console.warn(myLib);
    

    tsc 做正确的事并从 .ts 文件中解析类型,在生成的 javascript 中保留扩展名

    【讨论】:

    • 非常感谢!你知道为什么我不能使用 es5 并得到这个“未捕获的 ReferenceError:未定义导出”我的 index.html 中有 require.js
    • 定位es5时,生成的javascript中的默认模块格式为CommonJS,不能在浏览器中使用。您可以通过指定"module": "amd""module": "umd" 来覆盖默认选项(请参阅typescriptlang.org/docs/handbook/compiler-options.html)。 amd 应该与 require.js 一起使用
    • 添加模块后:“amd”我得到“main.js:1 Uncaught ReferenceError:define is not defined”。听起来可能很傻,但我找不到要下载的 amd.js 文件。
    • 使用amd 对我来说很好。请确保以 amd 方式加载您的文件:&lt;script data-main="main" src="require.js"&gt;
    猜你喜欢
    • 2014-10-16
    • 2016-12-24
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多