【问题标题】:Why does TypeScript transpilation to target: ES5, Module: CommonJS cause errors in the browser?为什么 TypeScript 转译到 target: ES5, Module: CommonJS 会导致浏览器出错?
【发布时间】:2020-05-30 14:41:13
【问题描述】:

我正在使用 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 引擎中运行”,我希望它能够在铬。

我的 tsconfig.json 是:

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

我刻意尝试让所有内容尽可能简单,因为我正在尝试学习一些关于测试、环境设置和节点的具体知识。可能是我太极简了。

如果我将模块更改为 ES2015,则转译代码可以工作。我是否错误地使用了 CommonJS?这是否意味着只能在服务器上运行?

提前谢谢你。

【问题讨论】:

  • 浏览器不支持没有模块类型<script src="" type="module"></script> 的导出,即使这样也不是所有浏览器都支持。
  • 您可能需要通过上面的const exports= {}; Object.defineProperty 来为exports 实例化一个变量
  • "lib": ["es5", "es6", "dom"], 添加到compilerOptions
  • @GetOffMyLawn,我的脚本标签上有 type="module" 属性。
  • 浏览器根本不支持exports(虽然支持export)。看起来您已将编译器配置为专门为 node.js 编译。

标签: javascript typescript node-modules es6-modules


【解决方案1】:

ES5 & ES6 & DOM 库应该包含在你的编译中。 要添加这些库,请在 tsconfig.json

中添加 lib 属性
{
   "compilerOptions": {
     ...
     "lib": ["es5", "es6", "dom"],
     ...
   }
}

【讨论】:

  • "lib" 属性不是这种情况下的问题。我不太了解何时以 Node 为目标,何时以浏览器为目标,这是本研究的很大一部分原因。 “lib”属性可能会在本研究中的某个时候发挥作用,但我认为我还没有达到它。
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2021-12-23
相关资源
最近更新 更多