Fix "imported module is not a function" after moving to webpack 5
Why a library's default import breaks with "is not a function" after a webpack 5 build, and the small config fix for library authors.
You moved a library to webpack 5 and published it. Now the apps that use it crash with:
TypeError: mylib__WEBPACK_IMPORTED_MODULE_0___default(...) is not a function
Explained like you're five: the app asked for a toy, got a box with the toy inside, and tries to play with the box.
Why it happens
Look at the library's webpack config. This one is very common:
output: {
filename: 'mylib.commonjs2.js',
library: 'MyLib',
libraryTarget: 'commonjs2',
},
Webpack 4 ignored the name MyLib for commonjs2 builds and put your code straight into module.exports. Webpack 5 does what its docs say: with a name set, your code goes to module.exports.MyLib. So import MyLib from 'mylib' now gets the box { MyLib: ... } instead of the function.
The fix, for library authors
Drop the name from the CommonJS build:
output: {
filename: 'mylib.commonjs2.js',
library: { type: 'commonjs2' },
},
Rebuild and publish a patch version, and the old imports work again. If your entry uses export default and you also want require('mylib') to return it directly, add export: 'default' to the library object.
A quick workaround, for library users
Until the library is fixed, check what you actually receive:
import * as mylib from 'mylib'
console.log(mylib)
The function is in there somewhere, usually under the library's name. Call it from there, or pin the last version that worked, and send the author a link to this fix.
In short: in webpack 5, commonjs2 plus a library name wraps your export in an object. Remove the name and the default import works again.
Get your project quote
Free result within 48-72 hours
Related insights
What to do when an open-source package is no longer maintained
A short checklist for an abandoned npm or pip dependency. Confirm it's abandoned, find a maintained fork, check the license and switch safely.
How to back up a SQL database so it actually works
A simple backup routine for PostgreSQL and MySQL. Dump the data, copy it off the server, run it on a schedule and check that you can restore.
Forward a remote port to your computer with SSH
Use ssh -L to open a database, admin panel or debug server that runs on a remote server on your own localhost, without opening it to the internet.