首页 文章

TypeError:__ webpack_require __ . i(...)不是函数

提问于
浏览
10

当我尝试简化导入时,我得到一个webpack TypeError . 以下代码无任何问题 . 这里我从 core/components/form/index.js 导入一个名为 smartForm 的React高阶组件(HOC) .

core/components/form/index.jssmartForm 的命名导出)

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(...)不是函数(...)

我错过了什么?

附:以下是我使用的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",

2 回答

  • 4

    tl;博士

    • 对于提问者:将此添加到 webpack.config.js
    resolve: {
      alias: {
        core: path.join(__dirname, 'core'),
      },
    },
    
    • 对于一般受众:确保您尝试导入的内容确实存在于该包中 .

    解释

    提问者的问题:导入自己的代码,如npm模块

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

    如果没有前导'/',' . /'或'../'来表示文件,则模块必须是核心模块或从node_modules文件夹加载 .

    因此,您要么必须执行Waldo JeffersSpain Train建议并编写 import { smartForm } from './core' ,或者您可以配置webpack以便它可以通过its aliases解决导入路径,这些路径是为解决此问题而创建的 .

    一般调试错误消息

    如果您尝试从现有的npm包(在 node_modules 中)导入某些内容但是 the imported thing doesn't exist in the exports ,则会出现此错误 . 在这种情况下, make sure there were no typos 并且您尝试导入的给定内容确实在该包中 . 现在,将库分成多个npm包是很时髦的, you might be trying to import from a wrong package .

    所以,如果你得到这样的东西:

    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 导出(或者它不是函数),所以我们需要检查我们的导入内容 .

  • 1

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

相关问题