Skip to content

Instantly share code, notes, and snippets.

@maneetgoyal
Last active October 11, 2020 07:05
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 maneetgoyal/c3c53f9cde666acc04db37133aa0d3f0 to your computer and use it in GitHub Desktop.
Save maneetgoyal/c3c53f9cde666acc04db37133aa0d3f0 to your computer and use it in GitHub Desktop.
Externalize peerDependency in Webpack
function getPeerDependencies() {
const pkgPath = path.join(process.cwd(), "./package.json");
const pkgJSON = JSON.parse(readFileSync(pkgPath));
const peerDependencies =
pkgJSON.peerDependencies !== undefined
? Object.keys(pkgJSON.peerDependencies)
: [];
return peerDependencies;
}
/**
* Considering UMD output target for Webpack
*/
function getExternals() {
const externalsDependencies = getPeerDependencies();
const externalsDictionary = {
// Ref: https://webpack.js.org/configuration/externals/#object
// Ref: https://github.com/webpack/webpack/issues/1275#issuecomment-245990108
react: {
root: "React",
commonjs: "react",
commonjs2: "react",
amd: "react",
},
"react-dom": {
root: "ReactDOM",
commonjs: "react-dom",
commonjs2: "react-dom",
amd: "react-dom",
},
"@material-ui/core": {
root: "MaterialUI",
commonjs: "@material-ui/core",
commonjs2: "@material-ui/core",
amd: "@material-ui/core",
},
};
let externals = {};
for (let i = 0; i < externalsDependencies.length; i += 1) {
if (externalsDependencies[i] in externalsDictionary) {
externals = {
...externals,
[externalsDependencies[i]]:
externalsDictionary[externalsDependencies[i]],
};
}
}
return externals;
}
// Webpack config:
module.exports = (env) => {
// do whatever with your config
let config = {...};
// Externalize peerDependencies (assuming UMD output target)
config = {...config, externals: {...config.externals, ...getExternals()};
return config;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment