当我尝试简化导入时,我得到一个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.js ( smartForm
的命名导出)
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 回答
tl;博士
webpack.config.js
:解释
提问者的问题:导入自己的代码,如npm模块
您尝试以与从
node_modules
文件夹中的npm包导入内容相同的方式导入模块的导出:import { something } from 'packagename';
. 这样做的问题是开箱即用 . Node.js docs给出了原因的答案:因此,您要么必须执行Waldo Jeffers和Spain 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 .所以,如果你得到这样的东西:
要获得有关应检查哪些导入的更多信息,只需打开webpack生成的输出文件,然后转到错误堆栈中最顶行标记的行(在本例中为165080) . 你应该看到类似的东西:
__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_9_react_router_dom__["match"])
. 这告诉我们react-router-dom
中没有match
导出(或者它不是函数),所以我们需要检查我们的导入内容 .由于
core
是您的应用程序的文件夹而不是npm模块,因此Webpack无法理解您要加载哪个文件 . 您必须使用指向文件的正确路径 . 您必须通过import { smartForm } from './core/index.js
替换import { smartForm } from 'core';