TypeError: __webpack_require__.i(...) is not a function

TypeError: __webpack_require__.i(...) is not a function

我在尝试简化导入时收到 webpack TypeError。以下代码可以正常工作。在这里,我从 core/components/form/index.js.

导入一个名为 smartForm 的 React 高阶组件 (HOC)

core/components/form/index.js(执行 smartForm 的命名导出)

export smartForm from './smart-form';

login-form.jsx(导入并使用smartForm

import { smartForm } from 'core/components/form';
class LoginForm extends React.Component {
    ...
}
export default smartForm(LoginForm);

但是,我想将导入简化为 import { smartForm } from 'core'。所以我在 core/index.js 中重新导出 smart-form 并从 core 导入它。请看下面的代码:

core/index.jssmartForm 的命名导出)

export { smartForm } from './components/form';
// export smartForm from './components/form';  <--- Also tried this

login-form.jsx(导入并使用smartForm

import { smartForm } from 'core';
class LoginForm extends React.Component {
    ...
}
export default smartForm(LoginForm); // <--- Runtime exception here 

此代码编译没有任何问题,但我在 export default smartForm(LoginForm);:

行收到以下运行时异常

login-form.jsx:83 Uncaught TypeError: webpack_require.i(...) is not a function(…)

我错过了什么?

P.S。以下是我使用的 Bable 和插件版本:

"babel-core": "^6.18.2",
"babel-preset-es2015-webpack": "^6.4.3",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-1": "^6.16.0",

由于 core 是您应用程序的文件夹而不是 npm 模块,Webpack 无法理解您要加载哪个文件。您必须使用指向文件的正确路径。您必须将 import { smartForm } from 'core'; 替换为 import { smartForm } from './core/index.js

tl;博士

  • 对于提问者:将此添加到您的 webpack.config.js:

    resolve: {
      alias: {
        core: path.join(__dirname, 'core'),
      },
    },
    
  • 对于一般观众:确保您尝试导入的东西确实存在于该包中。

说明

提问者的问题:像npm模块一样导入自己的代码

您尝试以与从 node_modules 文件夹 import { something } from 'packagename'; 的 npm 包中导入内容相同的方式导入模块的导出。这个问题是开箱即用的。 Node.js docs 给出原因的答案:

Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

因此,您要么必须执行 and suggested and write import { smartForm } from './core', or you can configure webpack so it can resolve your import path via its aliases 为解决这个确切问题而创建的内容。

一般调试错误信息

如果您尝试从现有的 npm 包(在 node_modules 中)导入某些内容,但 导入的内容不存在于导出 中,则会出现此错误。在这种情况下,确保没有拼写错误 并且您尝试导入的给定内容确实在该包中。现在流行将库分成多个 npm 包,你可能试图从错误的包中导入

所以如果你得到这样的结果:

TypeError: __webpack_require__.i(...) is not a function  
   at /home/user/code/test/index.js:165080:81  
   at Layer.handle [as handle_request] (/home/user/code/test/index.js:49645:5)

要获取有关应检查哪些导入的更多信息,只需打开 webpack 生成的输出文件,然后转到错误堆栈中最顶层标记的行(在本例中为 165080)。您应该会看到类似这样的内容:__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_9_react_router_dom__["match"])。这告诉我们 react-router-dom 中没有 match 导出(或者有但不是函数),因此我们需要检查该导入周围的内容。

出现这个错误的原因有很多。当我在 file-loader 中添加 js 时遇到此错误,然后当我删除它时它开始正常工作。

 {
     test: /\.(ttf|eot|svg|gif|jpg|png|js)(\?[\s\S]+)?$/,
     use: 'file-loader'
 },

当我删除 |js 时它起作用了

 {
     test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/,
     use: 'file-loader'
 },