Fix __webpack_imported_module_ is not a function for webpack5

Today, 27th January 2023, Ukraine is still bravely fighting for democratic values, human rights and peace in whole world. Russians ruthlessly kill all civilians in Ukraine including childs and destroy their cities. We are uniting against Putin’s invasion and violence, in support of the people in Ukraine. You can help by donating to Ukrainian's army.

This fix is relevant to you if you had a library on webpack4 or webpack3 that exported a function and after update to webpack5 in apps that import this library you started to see:

TypeError: <library_name>__WEBPACK_IMPORTED_MODULE_<somenumber>___default() is not a function

This happened for one of my packages and library user created an issue about TypeError.

I spent some time investigating it and it turned out that now webpack started to wrap the exported function in the object. So my previous builds of library worked fine with the next syntax:

import Painterro from 'painterro'

And now the only way to make it work was:

import { Painterro } from 'painterro'

This way is called named import, not so bad actually, there are a lot of advantages comparing to my previous export default method.

But for a library that already has 50k downloads on npm without fallback to previous behavior would be the road to pain:

Painterro yearly download stat

Yes, it is possible to explain the change in npm notice, add bold text in Readme, bump the minor number according to semver, but anyway, we would find users which will start asking why it is not working. Other users will just drop away the idea to use the library once face this issue.

So I created a minimal reproducible example and issue on webpack repo and the project member quickly explained what happened:

Because it was bug in v4 and now it is fixed, using library: 'P2', means module.exports.P2 = {}, but if you don't need it, just remove library: 'P2', and keep libraryTarget: 'commonjs2'

Thing is that I indeed had a library: 'Painterro', in module.exports.output in webpack.config.js :

module.exports = { 
 output: {
    path: path.resolve(__dirname, 'build'),  // folder where library will be placed
    filename: 'painterro.commonjs2.js',  // filename of the library
    library: 'Painterro',  // ⏪ this is the issue
    libraryTarget: 'commonjs2',

So what I did is just removed library: 'Painterro' and previous behavior returned back!

Ivan Borshchov profile picture
Feb 14, 2021
by Ivan Borshchov
Did it help you?
Yes !

Best related