繁体   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