Is it possible to create custom resolver in webpack?
I have my own convention when require modules. E.g. require("./components/SettingsPanel");
should be resolved to require("./components/SettingsPanel/SettingsPanel.js");
Is there any way to create such resolver?
Yes, it's possible. To avoid ambiguity and for easier implementation, we'll use a prefix hash symbol as marker of your convention:
require("#./components/SettingsPanel");
Then add this to your configuration file (of course, you can refactor it later):
var webpack = require('webpack');
var path = require('path');
var MyConventionResolver = {
apply: function(resolver) {
resolver.plugin('module', function(request, callback) {
if (request.request[0] === '#') {
var req = request.request.substr(1);
var obj = {
path: request.path,
request: req + '/' + path.basename(req) + '.js',
query: request.query,
directory: request.directory
};
this.doResolve(['file'], obj, callback);
}
else {
callback();
}
});
}
};
module.exports = {
resolve: {
plugins: [
MyConventionResolver
]
}
// ...
};
Created an updated example to work with Webpack v4. Purposely did not use ES6 syntax for backwards compatibility. You can make it a class if you wish.
You can read more about resolver examples at https://github.com/webpack/enhanced-resolve.
Thanks Ricardo for supplying the original answer.
var webpack = require('webpack');
var path = require('path');
function MyConventionResolver (source, target) {
this.source = source || 'resolve';
this.target = target || 'resolve';
}
MyConventionResolver.prototype.apply = function(resolver) {
var target = resolver.ensureHook(this.target);
resolver.getHook(this.source).tapAsync('MyConventionResolver', function(request, resolveContext, callback) {
if (request.request[0] === '#') {
var req = request.request.substr(1);
var obj = Object.assign({}, request, {
request: req + '/' + path.basename(req) + '.js',
});
return resolver.doResolve(target, obj, null, resolveContext, callback);
}
callback();
});
}
// In your Webpack Config
module.exports = {
...
resolve: {
plugins: [new MyConventionResolver()]
}
};