Last active
April 30, 2018 04:14
-
-
Save nyteshade/f4b4f5cc6fad6f91196902e2858168d9 to your computer and use it in GitHub Desktop.
Run webpack on the fly
This file contains hidden or 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
#!/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); |
Author
nyteshade
commented
Oct 11, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment