簡體   English   中英

如何在純TypeScript項目中修復“ReferenceError:exports not defined”?

[英]How to fix “ReferenceError: exports is not defined” in a pure TypeScript project?

如果我使用任何類型的導入或導出指令編寫.ts,生成的.js將在HTML頁面中加載時生成以下錯誤:“ReferenceError:exports not defined”

如何重現:

  1. 在VS中創建一個空的Node.js Web應用程序項目
  2. 添加帶有導入或導出行的.ts
  3. 添加一些HTML來調用生成的.js
  4. 啟動HTTP服務器( http-server -g [port] )並訪問您的HTML

我試過了:

  • 針對ES 5
  • 從tsconfig.json`中刪除行"module": "commonjs"
  • 安裝CommonJS和SystemJS
  • 使用tsc編譯.ts
  • 任何其他解決方案Stack Overflow都有類似的問題
  • 以上所有可能的排列。

我的.ts(如果它有導入指令可以是任何東西):

import { setTimeout } from "timers";
setTimeout(() => console.log("asdf"), 1000);

HTML只有一個引用腳本的簡單主體

我的package.json

{
  "name": "nodejs-web-app4",
  "version": "0.0.0",
  "description": "NodejsWebApp4",
  "main": "server.js",
  "author": {
    "name": ""
  },
  "devDependencies": {
    "@types/node": "^8.0.14"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": ["es6"],
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

結果.js:

從VS build(導致ReferenceError: exports is not defined ):

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const timers_1 = require("timers");
timers_1.setTimeout(() => console.log("asdf"), 1000);
//# sourceMappingURL=home-script.js.map

從命令tsc [filename].ts (導致ReferenceError: exports is not defined ):

"use strict";
exports.__esModule = true;
var timers_1 = require("timers");
timers_1.setTimeout(function () { return console.log("asdf"); }, 1000);

從VS Build但從"module": "commonjs"刪除"module": "commonjs" (導致SyntaxError: import declarations may only appear at top level of a module ):

import { setTimeout } from "timers";
setTimeout(() => console.log("asdf"), 1000);
//# sourceMappingURL=asdf.js.map

所有的HTML和ts都將被稱為“靜態”(沒有MVC)

使用http-server從我的VS項目中查看靜態HTML是不對的? 這是問題嗎?

應該建立任何其他方式? 使用不同的設置?

我有一個解決方法(即,在同一個TypeScript文件中保留我需要的所有內容),但令我困惑的是,我無法使用Node / TS創建和可視化一個簡單的項目。

瀏覽器不支持commonjs模塊。 您需要使用一些工具(webpack,匯總,browserify)在編譯后捆綁您的模塊。

如果刪除tsconfig.json中的module選項,或者設置為es2015esnext ,則導入導出語句將保留原始文件中的狀態。

import { foo } from './bar.js';

export default class Baz {}

它可以工作,因為一些瀏覽器已經支持本機ES模塊,但是有必要在腳本標記中添加一個類型屬性並將其設置為模塊

<script type="module" src="foo.js"></script>

如果不這樣做,您將收到一些錯誤,例如' SyntaxError:import聲明可能只出現在模塊頂層 '。

暫無
暫無

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

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