Skip to content

Instantly share code, notes, and snippets.

@Aghassi
Last active August 13, 2020 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aghassi/cf3e2aa1c38b285ed877ea113b8a75fc to your computer and use it in GitHub Desktop.
Save Aghassi/cf3e2aa1c38b285ed877ea113b8a75fc to your computer and use it in GitHub Desktop.
Create vendor chunks with scoped modules for webpack
/**
* Given the package.json of a repo and the webpack externals, construct an object of
* vendor chunks specifically for each scoped package (e.g. `@babel`)
* @param {Array} externals the list of packages external to the webpack build
* @param {Object} pkg the package.json for the current repository
* @returns {Object} An object of the form:
*
* @example
* ```javascript
* {
* babel:
* { test: /\/node_modules\/@babel\//,
* chunks: 'all',
* name: 'babel',
* priority: 0,
* enforce: true },
* }
* ```
*/
module.exports = (externals, pkg) => {
// Get all the dependencies from the package.json file
const cacheGroups = Object.keys(pkg.dependencies).reduce((groups, dependency) => {
// Match any that have a scope associated with them (e.g. `@babel`)
const [, scope] = dependency.match(/(@[\w-]+\/)?(.*)/);
// If they have a scope and are not externalized from the bundle
if (scope && !externals.includes(dependency)) {
// Create the name without @ and /
const chunkName = scope.replace('@', '').replace('/', '');
// Create an object for the chunk
if (!groups[chunkName]) {
// eslint-disable-next-line no-param-reassign
groups[chunkName] = {
test: new RegExp(`/node_modules/${scope}`),
chunks: 'all',
priority: 0,
enforce: true,
};
}
}
return groups;
}, {});
return cacheGroups;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment