尝试按照官方手册实现一个模块,我得到这个错误消息:

Uncaught ReferenceError:未定义exports 在app.js: 2

但在我的代码中,我从未使用过名称exports。

我该如何解决这个问题?


文件

app.ts

let a = 2;
let b:number = 3;

import Person = require ('./mods/module-1');

模块- 1. t

 export class Person {
  constructor(){
    console.log('Person Class');
  }
}
export default Person;

tsconfig.json

{
   "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true,
        "outDir": "scripts/"
    },
    "exclude": [
        "node_modules"
    ]
}

当前回答

对于一些ASP。NET项目的导入和导出可能根本不会在Typescripts中使用。

当我试图这样做时,问题的错误出现了,我后来才发现,我只需要像这样将生成的JS脚本添加到视图:

<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>

其他回答

对于一些ASP。NET项目的导入和导出可能根本不会在Typescripts中使用。

当我试图这样做时,问题的错误出现了,我后来才发现,我只需要像这样将生成的JS脚本添加到视图:

<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>

没有直接回答这个问题,但是没有stackoverflow线程提到这种情况,我花了一段时间来调试,所以在这里添加它,以防将来它可以帮助别人。

我有错误“导出未定义”来自导入的NPM模块。改变我的typescript配置没有任何作用,因为我无法控制导入的第三方代码。问题是该包的导入语法无效。例如,我已经导入了“@mui/material/TextField/TextField”,但正确的导入应该是“@mui/material/TextField”。

一个解决方案:

从package.json中删除"type": "module"。

首先,在你的公共文件夹中找到你的index.html,找到脚本的引用<script src="myScript.js"></script>,并添加type="module"

像这样:

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

其次,在您的tsconfig中。Json,确保目标设置为es5,模块设置为es2015

 "compilerOptions": {
    "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    /* Modules */
    "module": "es2015", /* Specify what module code is generated. */
}

注意:确保使用.js扩展名导入,例如import Piece from './classes/ Piece .js'

我认为问题可能是配置不匹配。

下面的工作解决方案1为您提供了ES模块的正确配置。 下面的工作解决方案2为您提供了正确的CommonJS配置。 混合解决方案1+2给你一个错误。

为了清晰起见,我在这里只发布了部分内容。 Github项目https://github.com/jmmvkr/ts-express/ 准备一套完整的文件来演示工作解决方案1和解决方案2。

工作方案1,ES模块

/* Configuration for ES Module */

// tsconfig.json
{
    "compilerOptions": {
        "module": "es6", // or "esnext"
    }
}
// package.json
{
    "type": "module", // type is module
}

工作解决方案2,CommonJS

/* Configuration for CommonJS */

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
    }
}
// package.json
{
    "type": "", // type is NOT module
}

混合,不工作

/* Mixed, got ReferenceError: exports is not defined in ES module scope */

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
    }
}
// package.json
{
    "type": "module", // type is module
}