Last active
March 8, 2020 08:50
-
-
Save emilio-martinez/2ab69751feb5e7550886903a58a0874f to your computer and use it in GitHub Desktop.
Rough function to write a Webpack config to a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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