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

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

当前回答

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

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

其他回答

试试@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"
  }
};

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

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

通过将模块编译器选项设置为es6可以解决这个问题:

{
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}

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

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

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

对我来说,从tsconfig中删除“esModuleInterop”:true。Json成功了。