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

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"
    ]
}

当前回答

首先,在你的公共文件夹中找到你的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'

其他回答

在其他JavaScript引用之前添加以下行。这是一个不错的小hack。

<script>var exports = {};</script>

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

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

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

我在SSR客户端部分中遇到了这样的错误,因为它使用了一个用tsconfig构建的库。什么带来使用CommonJS模块解析tsc CLI选项编译器选项:目标=== "ES3"或"ES5" ?CommonJS: ES6。当它使用目标ESNext时。

如果您只是为类型使用接口,那么省略export关键字,ts可以在不需要导入的情况下获取类型。关键是你不能在任何地方使用导入/导出。

export interface Person {
   name: string;
   age: number;
}

into

interface Person {
   name: string;
   age: number;
}

我有类似的问题,原来的海报的问题:

我最好告诉你我犯了什么错误以及我是如何改正的,这可能会帮助到别人。

我有javascript nodejs项目,并将其转换为typescript。

之前的包装。我有“类型”:“模块”当我在JavaScript运行。

当我把它转换成TypeScript项目,并开始转换.ts文件中的文件,并使用以下命令开始运行:

npx tsc test.ts && node test.ts

我会得到上面的错误。

我通过简单地从package.json中删除“type”:“module”来摆脱这个错误

我的tsconfig。Json格式如下:

{
    "compilerOptions": {
        "target": "esnext",
        "lib": ["es6", "es5", "es7", "dom"],
        "allowJs": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "es6",
        "outDir": "./build",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "skipLibCheck": true
    },
    "exclude": ["node_modules", "build"]

我使用节点14和TypeScript 4.2.4