Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Last active April 30, 2018 04:14
Show Gist options
  • Save nyteshade/f4b4f5cc6fad6f91196902e2858168d9 to your computer and use it in GitHub Desktop.
Save nyteshade/f4b4f5cc6fad6f91196902e2858168d9 to your computer and use it in GitHub Desktop.
Run webpack on the fly
#!/usr/bin/env node --harmony
// Fetch the Path, File System and Child Process modules
var Path = require('path');
var FS = require('fs');
var CP = require('child_process');
/**
* The actual webpack config is stored within a function and then
* extracted as a string as this preserves the regular expression
* definitions whereas JSON.stringify does not.
*/
var webpackConfigFn = function(){
module.exports = {
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
entry: {},
target: 'node',
output: {
path: './lib',
filename: '[name].bundle.js',
libraryTarget: 'commonjs2'
},
module: {
loaders: [
{
test: /\.js$/i,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json$/i,
loader: 'json-loader'
}
]
}
};
}
// This should be hardened; fetch the "first" param as a name
var targetName = process.argv[2];
// This should be hardened; fetch the "second" param as a path and resolve it
var targetPath = Path.resolve(process.argv[3]);
// Extract, modify and prepare the webpack configuration.
var codeString = webpackConfigFn
.toString()
.replace(/function \(\)\{/, '')
.replace(/entry\: \{\}/, `entry: {${targetName}: '${targetPath}'}`);
// Get rid of the that last pesky closing brace from the function
codeString = codeString.substring(0, codeString.lastIndexOf('}'));
// Create a temporary directory (requires node >5; maybe just use /tmp?)
var tmpDir = FS.mkdtempSync('webpack', 'utf8');
// Create the path with the temporary directory
var tmpPath = Path.join(tmpDir, 'webpack.config.js');
// Write the webpack config to the temporary directory
FS.writeFileSync(tmpPath, codeString);
// Spit out the config so it can be seen visually
console.log('\033[1;4mWebpack Config\033[0m%s', codeString);
// Run webpack
CP.execSync(
`webpack --config ${tmpPath}`,
{
cwd: __dirname,
env: process.env,
stdio: [
process.stdin,
process.stdout,
process.stderr
]
}
);
// Remove the config file
FS.unlinkSync(tmpPath);
FS.rmdirSync(tmpDir);
@nyteshade
Copy link
Author

screen shot 2016-10-11 at 10 35 15 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment