React 16.14.0:未捕获错误 ReferenceError:未定义导出

Ara*_*oca 9 javascript typescript reactjs webpack next.js

我是next-translate库的作者,我正在开发一个实验版本,我在 React 16.14.0 中遇到错误,我不明白为什么会发生这种情况。将 React 升级到版本 17 然后它工作正常,但我不想强迫每个使用我的库的新版本的人迁移他们的 React 版本。

我创建了一个可重现的错误示例:https : //github.com/aralroca/next-translate-error-reproduction

为了重现这个问题:

  • 克隆这个 repo
  • yarn && yarn dev
  • 打开 localhost:3000
  • 打开开发者工具

Error was not caught ReferenceError: exports is not defined

我的库的预发布代码在这里:

配置文件

{
  "compilerOptions": {
    "strict": false,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "removeComments": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "declaration": true,
    "lib": ["esnext", "dom"],
    "allowJs": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./lib/esm"
  },
  "include": ["./src"]
}
Run Code Online (Sandbox Code Playgroud)

tsconfig-cjs.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "./lib/cjs",
    "declaration": false
  }
}
Run Code Online (Sandbox Code Playgroud)

这是包代码:

如果有人知道此错误的来源并可以帮助我,我将不胜感激!我已经尝试解决它好几天了,但我有点迷茫,因为我不知道为什么会这样......谢谢!

注意:看起来它只发生在开发中,做得yarn build && yarn start很好。

hac*_*ape 1

很高兴您发现了该错误,这是您的案例的解释。

我们来比较一下两个版本的编译结果:

查看两个文件1.0.0-experimental.14 1.0.0-experimental.15中的 ln:54 。

var react_1 = __importDefault(require("react"));

// The key different is the exclusion of this line:
var app_1 = __importDefault(require("next/app"));

var I18nProvider_1 = __importDefault(require("./I18nProvider"));
var loadNamespaces_1 = __importDefault(require("./loadNamespaces"));
Run Code Online (Sandbox Code Playgroud)

因为您不再使用App.getInitialProps(),所以import App from 'next/app'TypeScript 也会删除它。真正的问题在于next/app模块。

在面包屑中,我们看到next/app简单的再导出next/dist/pages/_app

module.exports = require('./dist/pages/_app')
Run Code Online (Sandbox Code Playgroud)

至于内容./dist/pages/_app,请查看此链接。它exports到处都被引用为全局变量,这导致了问题:Error was not caught ReferenceError: exports is not defined

问题很明显,该代码next/dist/pages/_app.js包含在发送到网页的捆绑 JS 代码中,而没有被 webpack 正确转译。

但在此之后我无法提供进一步的帮助,因为我不熟悉堆栈next.js。我猜你需要调整 webpack 配置来对该exports全局变量执行一些操作。