繁体   English   中英

浏览器中的Typescript产生`ReferenceError:require未定义`

[英]Typescript in browser produces `ReferenceError: require is not defined`

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

未捕获的ReferenceError:未定义require

根据https://stackoverflow.com/a/38531466/1663462我应该'将所有文件捆绑成一个'我试过设置:

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

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

1导入*作为Highcharts来自“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

根据https://stackoverflow.com/a/38531466/1663462我应该'将所有文件捆绑成一个' "outFile": "compiled.js"

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

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

这实际上在链接的答案中也提到了👍🏻

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM