Skip to content

Instantly share code, notes, and snippets.

@Munter
Created May 14, 2020 15:58
Show Gist options
  • Save Munter/3434527e317f899fc8f9103fd5bb624d to your computer and use it in GitHub Desktop.
Save Munter/3434527e317f899fc8f9103fd5bb624d to your computer and use it in GitHub Desktop.
Get all entrypoints referenced by a webpack configuration
// @ts-check
const { resolve } = require('path');
/** @typedef {import('webpack/declarations/WebpackOptions').WebpackOptions} WebpackOptions */
/** @typedef {import('webpack/declarations/WebpackOptions').Entry} Entry */
/**
* @param {string} webpackConfigPath
*/
module.exports = async function getEntrypointsFromWebpackConfig(
webpackConfigPath
) {
const configs = await resolveConfig(require(webpackConfigPath));
const entryPoints = (await Promise.all(
configs.map(async ({ context, entry }) => {
if (typeof entry === 'undefined') {
throw new Error(`Webpack configuration must contain 'entry' property`);
}
const paths = await resolveEntry(entry);
if (context) {
return paths.map(p => resolve(webpackConfigPath, context, p));
} else {
return paths.map(p => resolve(webpackConfigPath, p));
}
})
)).flat();
return [...new Set(entryPoints.sort())];
};
/**
* @param {Entry} entry
* @returns {Promise<string[]>}
*/
async function resolveEntry(entry) {
if (typeof entry === 'function') {
return resolveEntry(await entry());
}
if (Array.isArray(entry)) {
return entry;
}
if (typeof entry === 'string') {
return [entry];
}
// By this point we can assume entry to be an Object
const objectValues = await Promise.all(
Object.values(entry).map(resolveEntry)
);
return objectValues.flat();
}
/**
* @param {WebpackOptions | WebpackOptions[] | function() : (WebpackOptions | WebpackOptions[] | Promise<WebpackOptions> | Promise<WebpackOptions[]>)} config
* @returns {Promise<WebpackOptions[]>}
*/
async function resolveConfig(config) {
if (typeof config === 'function') {
return await resolveConfig(await config());
}
if (Array.isArray(config)) {
const results = await Promise.all(config.map(resolveConfig));
return results.flat();
}
return [config];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment