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

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

当前回答

简单地添加libraryTarget: 'umd',就像这样

const webpackConfig = {
  output: {
    libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
  }
};

module.exports = webpackConfig; // Export all custom Webpack configs.

其他回答

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

所以这是一个超级通用的TypeScript错误,这个StackOverflow问题是我研究我的问题的各种查询的第一个结果。它有38.5万的浏览量。

对于那些使用Angular / TypeScript和Angular库使用ng-packagr时看到通用的“ReferenceError: exports is not defined”的人,你需要定义public-api。每个功能/组件/服务的t,这样你就可以将它包含在索引中。例如在这篇文章的回购中找到的

节点16或18(下周LTS为18) Angular 2+(目前有14个) 打印稿4.6.4-4.8.2

一些简单的例子类似于引用Creating Libraries

ng new workspace --no-create-application
cd workspace
ng generate app home --routing=true --style=scss
ng generate app admin --routing=true --style=scss
ng generate library lib
... # include your library 'lib' into your application 'home'
ng build lib --watch &
ng serve home --open

没有直接解释的是你的索引。Ts和public-api。Ts文件需要在每个特性/组件/服务中。如果你有一个复杂的库,比如下面回购中的这些示例特性A、B和C。回购有以下几点:

src / lib 一个 索引。Ts(只引用。/public-api) 公共api。Ts(只引用目录中导出的文件) 功能b 索引。Ts(只引用。/public-api) 公共api。Ts(只引用目录中导出的文件) feature-c 索引。Ts(只引用。/public-api) 公共api。Ts(只引用目录中导出的文件)

有同样的问题,并通过改变JS包的加载顺序来修复它。

检查调用所需包的顺序,并按适当的顺序加载它们。

在我的特定情况下(不使用模块绑定器),我需要加载Redux,然后Redux坦克,然后React Redux。在Redux坦克之前加载React Redux会给我出口是没有定义的。

我的解决方案是上面所有东西的总和,我添加了一些小技巧,基本上我把这个添加到我的html代码中

<script>var exports = {"__esModule": true};</script>
<script src="js/file.js"></script>

这甚至允许你使用import而不是require,如果你使用electron或其他东西,它在typescript 3.5.1, target: es3 -> esnext中工作得很好。

简单地添加libraryTarget: 'umd',就像这样

const webpackConfig = {
  output: {
    libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
  }
};

module.exports = webpackConfig; // Export all custom Webpack configs.