1

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'

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63

1 Answers1

1

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'],
  },
Zameer Haque
  • 394
  • 4
  • 24
  • Thanks. Your solution for me wasn't entirely complete but it steered me in the right direction. This didn't work - modules: ['node_modules', path.resolve(__dirname, '../mymicrobundle/dist')] but this did: { alias: { '@mymicrobundle': path.resolve(__dirname, '../mymicrobundle/dist') },} – Steve Tomlin Nov 19 '21 at 19:52
  • There was also another issue I realised with microbundle is that it doesn't default to bundling into an npm format - ie common js. I had to actually set the format to be --format cjs. Updating repo now to show fix. – Steve Tomlin Nov 19 '21 at 19:55
  • 1
    I was wrong. I got it working with: modules: [path.resolve(__dirname, '../microbundle')],I just had to remove the dist. Now I don't need the unnecessary alias. – Steve Tomlin Nov 20 '21 at 11:46