I understood you correctly: you essentially got
- React custom component library (built using Webpack build # 1)
- a React application that should use some (all) of these components (built with Webpack build # 2, completely separate from # 1)
?
If so, read on.
"Is this possible in the reaction?" instead, the question should be βIs this possible in Webpack?β and the answer is βYes.β The following is being tested with Webpack 2, but should also work with v.1.
Let me name your projects Lib
(your library of React component components) and App
(consumer library).
In the Lib
project:
Create an entry point file, say index.js
, which exports all custom React components as follows:
import {Button} from './button'; import {DatePicker} from './DatePicker'; import {TextBox} from './textBox'; export const MyComponentLib = { Button, DatePicker, TextBox };
Update webpack.config.js
so that the project combines the UMD library (it may also be "var") and set the entry point to the above index.js
file. This will make your library accessible through a global variable named MyComponentLib
(the name comes from export
above) in the consumer application later:
... output: { path: './dist', filename: 'mylib.bundle.js', libraryTarget: 'umd' }, ... entry: './index.js', ...
In the App
project:
In the index.html
file, you will have two <script>
: one for mylib.bundle.js
( Lib
project output), and the other for the App
project package itself. You may have more packages (application, provider, etc.), I just simplify the situation here.
Update webpack.config.js
to mark the component library as an external dependency. Here MyComponentLib
also the name of the global variable available to the library, and myComponents
is the name that should be used in import
statements:
... externals: { myComponents: 'MyComponentLib' }, ...
Now in the App
you can import the component as follows:
import {DatePicker} from 'myComponents';
This will dynamically load the DatePicker from the component library at runtime through a global variable.
Bonus: if you use eslint
, you do not want it to complain about missing modules, which, as you know, are external; add this to your .eslintrc
:
... "settings": { "import/core-modules": ["myComponents"] }, ...
source share