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

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

当前回答

我也有这个问题。然后我只是把“module”:“commonjs”改为“module”:“ESNext”,一切都正常工作。 这是tsconfig.json:

{
    "compilerOptions": {
      "module": "ESNext",
      "esModuleInterop": true,
      "target": "ESNext",
      "moduleResolution": "node",
      "sourceMap": true,
      "outDir": "dist",
    },
    "lib": ["ESNext"],
  }

希望它能解决你的问题!

其他回答

要解决这个问题,将这两行放在index.html页面中。

<script>var exports = {"__esModule": true};</script>
<script type="text/javascript" src="/main.js">

确保检查main.js文件路径。

对于仍然有这个问题的人,如果你的编译器目标设置为ES6,你需要告诉babel跳过模块转换。为此,将此添加到.babelrc文件中

{
  "presets": [ ["env", {"modules": false} ]]
}

npm安装@babel/plugin-transform- commonjs

添加到.babelrc插件解决了我的问题。

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

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

试试@iFreilicht上面建议的方法。如果在你安装了webpack之后没有工作,你可能只是从网上的某个地方复制了一个webpack配置,并在那里配置了你想要输出支持CommonJS的错误。确保在webpack.config.js中不是这样:

module.exports = {
  mode: process.env.NODE_ENV || "development",
  entry: { 
    index: "./src/js/index.ts"
  },
  ...
  ...
  output: {
    libraryTarget: 'commonjs',         <==== DELETE THIS LINE
    path: path.join(__dirname, 'build'),
    filename: "[name].bundle.js"
  }
};