簡體   English   中英

為什么 TypeScript 轉譯到 target: ES5, Module: CommonJS 會導致瀏覽器出錯?

[英]Why does TypeScript transpilation to target: ES5, Module: CommonJS cause errors in the browser?

我正在使用 TypeScript 和模塊,以便我可以使用 Jest 進行測試。 我能夠在 Jest 中很好地通過測試,但是轉換后的 JavaScript 無法在瀏覽器中運行。 我收到錯誤:

Uncaught ReferenceError: exports is not defined at scripts.js:2

轉譯后的 JavaScript 是:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true }); // this is the offending line
var root = document.documentElement;
exports.root = root;
var button = document.querySelector('button');
if (button) {
    button.addEventListener('click', handleClick);
}
function handleClick() {
    if (root)
        console.log(root.style.backgroundColor);
    var color = '#000000'.replace(/0/g, function () {
        return Math.floor(Math.random() * 16).toString(16);
    });
    if (root) {
        root.style.setProperty('--bg-color', color);
    }
}
exports.handleClick = handleClick;
var sum = function (a, b) {
    return a + b;
};
exports.sum = sum;

由於 TypeScript 聲明它“編譯為干凈、簡單的 JavaScript 代碼,可以在任何瀏覽器、Node.js 或任何支持 ECMAScript 3(或更新版本)的 JavaScript 引擎中運行”,我希望它可以在 Chrome 中運行。

我的 tsconfig.json 是:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "allowJs": true,
    "outDir": "./lib",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}

我特意盡量讓所有東西都保持簡單,因為我正在嘗試學習一些關於測試、環境設置和節點的具體知識。 可能我太極簡了。

如果我將模塊更改為 ES2015,則轉譯后的代碼將起作用。 我是否錯誤地使用了 CommonJS? 那是不是只能在服務器上運行?

先感謝您。

ES5 & ES6 & DOM 庫應該包含在你的編譯中。 要添加這些庫,請在tsconfig.json 中添加lib屬性

{
   "compilerOptions": {
     ...
     "lib": ["es5", "es6", "dom"],
     ...
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM