DevForth

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.

Ivan Borshchov
Ivan Borshchov
CEO & System Architect @ DevForth
Fix "imported module is not a function" after moving to webpack 5
Fix "imported module is not a function" after moving to webpack 5

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