varHarrie / varharrie.github.io

:blue_book: Personal blog site based on github issues.
https://varharrie.github.io
MIT License
3.66k stars 544 forks source link

找不到通过symlink引入的模块中的peerDependencies依赖 #26

Open varHarrie opened 5 years ago

varHarrie commented 5 years ago

最近在写一个React组件库,遇到了这么一个问题:

这个组件库my-components通过peerDependencies依赖了react

在一个Example项目(实质是storybook),我通过symlink的方式将my-components作为依赖,并且安装了react,结构如下:

Example |--node_modules | |--react | |--react-router | |--my-components (通过symlink引入,并且import * as React from 'react') |--src | |--index.js (import 'my-components') |--webpack.config.js

通过webpack运行起来时,提示报错:

ERROR in ../../my-components/index.js
Module not found: Error: Can't resolve 'react' in 'xxx/my-components/index.js'

并且,在my-components下,通过npm install react手动安装react时,不会出现错误。所以,几乎可以肯定是引入包时查找的目录除了问题。

在github上找到了类似的问题和答案,通过配置webpack.config.js,可以解决这个问题:

const path = require('path')

module.exports = {
  // ...
  resolve:  {
    symlinks: false
    // 或者
    // modules: [path.resolve(__dirname, './node_modules'), 'node_modules']
  }
  // ...
}

让依赖引入的查询位置在正确的目录上进行。