Webpack v4.42.0
I'm trying to get webpack to pickup my image assets in html img tags, but it doesn't seem to be respecting my webpack resolve aliases. As far as I've seen on other posts, I'm supposed to be able to prefix the string with the ~
character, but it doesn't seem to be working for me.
I get the following error: Error: Cannot find module '@assets/img/avatar_default.jpg'
This works (relative path):
<img src="../../../assets/img/avatar_default.jpg" />
This doesn't work (alias):
<img src="~@assets/img/avatar_default.jpg" />
I've got my webpack configured with the following aliases:
resolve: {
alias: {
'@': path.resolve(fs.realpathSync(process.cwd()),
'@assets': path.resolve(__dirname, 'src/assets/'),
}
}
And my html-loader config:
{
loader: 'html-loader',
options: {
minimize: false,
preprocessor: (content, loaderContext) => {
// Allow using EJS/underscore templating to process templates
// This is usually used for differences between different app builds (e.g. app vs. admin)
let result;
try {
result = ejs.render(content, {
_WHICH_APP_,
});
} catch (error) {
loaderContext.emitError(error);
return content;
}
return result;
},
}
}
Ok, so I figured it out.
The issue is related to extract-loader
and there's a fork + pull request out that's been waiting to be merged into the main repo since May 2020. See this GitHub issue or this pull request.
In order to fix this for myself, I needed to update the extract-loader
dependency in my package.json file to point to this fixed commit, and then add a postinstall script to build the extract-loader
after installing the fixed version.
package.json:
"scripts": {
"postinstall": "cd node_modules/extract-loader && yarn install && yarn build"
},
"devDependencies": {
"extract-loader": "https://github.com/vseventer/extract-loader#7f8b82f3d6800e5ad078880594fa577f4503c64e",
},
After updating your package.json file, just run yarn install
to update your dependencies and build the fixed extract-loader
, then re-run your webpack build. If you want to verify that you have the proper version of extract-loader
, you'll now see the error say ModuleNotFoundError: Module not found: Error: Can't resolve
instead of just Error: Cannot find module
.
For anyone reading this, do you know of an alternative to extract-loader that's still maintained? It's a bit worrying that this hasn't been fixed even though it's been identified with a working PR for a year.