【问题标题】:Typescript in browser produces `ReferenceError: require is not defined`浏览器中的打字稿产生`ReferenceError:未定义要求`
【发布时间】:2019-03-25 15:55:44
【问题描述】:

如果我尝试在浏览器中获取 index.js,则会收到以下错误:

Uncaught ReferenceError: require is not defined

根据https://stackoverflow.com/a/38531466/1663462,我应该“将所有文件打包成一个”,我尝试过设置:

"outFile": "compiled.js" 但是编译然后给我一个错误:

index.ts:1:1 - 错误 TS6131:无法使用选项编译模块 'outFile' 除非 '--module' 标志是 'amd' 或 'system'。

1 import * as Highcharts from "highcharts";



Found 1 error.

如果答案能解释为什么会发生这种情况,我会很感激,以及可能的解决方案(有各种类似的问题/答案只是盲目地建议像 CommonJS / systemjs 之类的东西)......


tsconfig.json

{
    "compilerOptions": {
        "allowJs": true,
        "sourceMap": true,
        "target": "es5",
    },
    "include": [
        "index.ts"
    ],

    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Highcharts = require("highcharts");
document.addEventListener('DOMContentLoaded', function () {
    var myChart = Highcharts.chart('container', {
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Fruit Consumption'
        },
        xAxis: {
            categories: ['Apples', 'Bananas', 'Oranges']
        },
        yAxis: {
            title: {
                text: 'Fruit eaten'
            }
        },
        series: [{
                name: 'Jane',
                data: [1, 0, 4]
            }, {
                name: 'John',
                data: [5, 7, 3]
            }]
    });
});
//# sourceMappingURL=index.js.map

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    根据https://stackoverflow.com/a/38531466/1663462,我应该“将所有文件打包成一个” "outFile": "compiled.js"

    outFile 不是在使用模块系统时将所有文件捆绑为一个的正确方法。

    改为使用 webpack (http://webpack.js.org/) 将所有模块捆绑到单个输出 .js 文件中。

    链接的答案中实际上也提到了这一点??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 2016-10-23
      • 2018-01-21
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多