Please see example repo https://github.com/inspiraller/webpack-and-microbundle
Microbundle code
mymicrobundle/src/index.js
import React from 'react'
const MyMicroBundle = ({session}) => {
return (
<div>Session = {session}</div>
)
}
export default MyMicroBundle
microbundle/package.json - for output
{
...
"source": "src/index.js",
"main": "dist/index.umd.js",
"module": "dist/index.module.js",
"exports": "dist/index.modern.js",
"unpkg": "dist/index.umd.js"
}
Importing Microbundle code
webpack-loads-microbundle/package.json
{
"dependencies": {
"@mymicrobundle/example": "file:../mymicrobundle",
}
}
webpack-load-microbundle/src/index.tsx
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import MyMicroBundle from '@mymicrobundle/example'
import './index.scss'
const App = () => {
const [session, setSession] = useState('')
return (
<div>
<h1>Hello</h1>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Note: The microbundle package is bundled as javascript, but I'm using typescript to import it. Though shouldn't make any difference. I'm also using pnpm instead of npm but also this should be fine as all other imports work.
Something about my path is wrong maybe.
Error
Module not found: Error: Can't resolve '@mymicrobundle/example' in 'C:\baps\react_all\webpack-and-microbundle\webpack-loads-microbundle\src'
CodePudding user response:
webpack resolves modules from its process.cwd()/node_modules
by default.
So in your case it is looking for @mymicrobundle/example
in webpack-and-microbundle
(the current working directory) which is your app directory.
You need to let webpack
know, where it needs to search in addition to your project's node_modules
.
This can be done using the resolve.modules
key. See docs: https://webpack.js.org/configuration/resolve/#resolvemodules
So your webpack config should have something like:
resolve: {
modules: ['node_modules', 'path/to/@mymicrobundle/example'],
},