I agree with the accepted answer that doing this for transitive dependencies is very risky, however, if you know what you are doing:
Another approach would be to write a custom Plugin based on the NormalModuleReplacementPlugin which will always resolve to an aliased version.
Let's say you always want to use lodash@4.17.2
when Webpack encounters require('lodash')
/ import lodash from 'lodash'
.
This is very useful if your non-webpack code (for example custom Node scripts) depend on a different version, but you'd like to use another version for runtime code.
// package.json
{
"dependencies": {
"lodash-for-webpack": "https://registry.npmjs.org/lodash/-/lodash-4.17.2.tgz",
"lodash": "^3.0.0"
}
}
const webpack = require('webpack');
// Match 'lodash', 'lodash/foo/bar', but not 'lodash-es' or 'webpack-lodash-plugin'
const lodashRegex = /lodash(?!-)(\/[a-zA-Z0-9\-_]*)*/;
function FixLodashVersionPlugin () {
return new webpack.NormalModuleReplacementPlugin(
lodashRegex,
function (resource) {
const segments = resource.request.split('/');
if (segments[0] === 'lodash') {
segments[0] = 'lodash-for-webpack';
resource.request = segments.join('/');
}
}
);
}
module.exports = {
FixLodashVersionPlugin
};
Note that in this example I directly link to a gzipped tarball, as documented in the npm install docs under b) and c). But you could also use the npm:
prefix.