Skip to content

Instantly share code, notes, and snippets.

@emilio-martinez
Last active March 8, 2020 08:50
Show Gist options
  • Save emilio-martinez/2ab69751feb5e7550886903a58a0874f to your computer and use it in GitHub Desktop.
Save emilio-martinez/2ab69751feb5e7550886903a58a0874f to your computer and use it in GitHub Desktop.
Rough function to write a Webpack config to a file
const { writeFileSync } = require('fs-extra');
const { EOL } = require('os');
/**
* Function to write a Webpack config to a file.
* Helpful when debugging a Webpack config from a tool or library.
* Several aspects here could be improved, but this is merely a rough take.
*
* @param {string} destPath
* @param {import('webpack').Configuration} config
*/
function writeWebpackConfigToFile(destPath, config) {
const stringified = JSON.stringify(
config,
(_, value) => {
// is RegExp
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return `/${value.source}/${value.flags}`;
}
// Serialize Typescript in a manageable format
if (
key.toUpperCase() === 'TYPESCRIPT' &&
'version' in value &&
'versionMajorMinor' in value
) {
return `{ [package code: typescript ${value.version}] }`;
}
// is function
if (typeof value === 'function') {
return value.toString();
}
return value;
},
' '
);
const fnRegExp = /\"(function(?:.*)})\"/gim;
const regexpRegExp = /\"(\/[^\*](?:.*)\/)\"/gim;
const somewhatRehydrated = stringified
.replace(regexpRegExp, (_, str) => str.replace(/\\\\/gim, '\\'))
.replace(/\"\{\s+(\[package code: (?:.+)\])\s+\}\"/gim, (_, str) => `{ /* ${str} */ }`)
.replace(fnRegExp, (_, str) =>
str
.replace(/(\\n)/gim, EOL)
.replace(/(\[native code\])/gim, str => `/* ${str} */`)
.replace(/(\\")/gim, '"')
.replace(/(\\\\')/gim, "\\'")
);
writeFileSync(destPath, `exports.module = () => {\nreturn ${somewhatRehydrated};\n};`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment