如何使用Webpack设置React组件的私有共享库 [英] How to set up a private shared library of React components with Webpack

查看:263
本文介绍了如何使用Webpack设置React组件的私有共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个Webpack项目中使用了许多React组件,我想通过NPM共享它们.我自然是这样:

I have a number of React components that I use in multiple Webpack projects, and I want to share them via NPM. So naturally I:

  1. 将这些组件放入(私有)GitHub存储库中
  2. 将该回购添加到主项目的package.json
  3. 为了能够同时在组件库上进行开发,我使用npm link将其符号链接到我的主项目中.
  1. put those components into a (private) GitHub repo
  2. Added that repo to a main project's package.json
  3. So that I could develop on the component library simultaneously, I used npm link to symlink it into my main project.

但是,Webpack无法从我的库组件文件中解析react,因为库项目文件夹或其任何父项中都没有node_modules.

However, Webpack can't resolve react from my library component files, because there's no node_modules in the library project folder or any of its parents.

我已经在Webpack配置的externals中看到了与react作为捆绑包构建的第三方React组件,但是我不想构建单独的捆绑包或做任何复杂的事情,我只想需要我的库组件的原始资源.有人知道怎么做吗?

I've seen 3rd party React components that were built as a bundle with react in the externals of the Webpack config, but I don't want to build a separate bundle or do anything complicated, I just want to require the raw source for my library components. Does anyone know how to do that?

推荐答案

我希望我能找到一个更优雅的解决方案,但是将其添加到我的webpack.config.js工作中:

I wish I could find a more elegant solution, but adding this to my webpack.config.js worked:

resolve: {
    fallback: path.resolve(__dirname, 'node_modules')
},
resolveLoader: { root: path.join(__dirname, "node_modules") },

但是,我最终决定仅在git子模块中的项目之间共享组件会更容易.

However, I ultimately decided it would be easier just to share the components between projects in a git submodule.

这篇关于如何使用Webpack设置React组件的私有共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆