簡體   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