Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Created July 21, 2020 18:15
Show Gist options
  • Save jgcmarins/1bbc6023b500969bc925e58388aca7cd to your computer and use it in GitHub Desktop.
Save jgcmarins/1bbc6023b500969bc925e58388aca7cd to your computer and use it in GitHub Desktop.
Run any Node.js script with webpack. Usage: babel-node webpackx.js ./path/to/script
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const cwd = process.cwd();
export const outputPath = path.join(cwd, '.webpack');
export const outputFilename = 'bundle.js';
export default {
context: cwd,
mode: 'development',
target: 'node',
devtool: false,
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json', '.mjs'],
},
output: {
libraryTarget: 'commonjs2',
path: outputPath,
filename: outputFilename,
pathinfo: false,
futureEmitAssets: true,
},
optimization: {
splitChunks: false,
removeEmptyChunks: false,
removeAvailableModules: false,
},
externals: [
nodeExternals({
whitelist: [/@package/],
}),
nodeExternals({
modulesDir: path.resolve(__dirname, '../node_modules'),
whitelist: [/@package/],
}),
],
module: {
rules: [
{
test: /\.mjs$/,
type: 'javascript/auto',
},
{
test: /\.(js|jsx|ts|tsx)?$/,
use: {
loader: 'babel-loader?cacheDirectory',
},
exclude: [/node_modules/, path.resolve(__dirname, '.webpack')],
},
],
},
plugins: [],
node: {
__dirname: false,
__filename: false,
fs: 'empty',
},
};
import path from 'path';
import { spawn } from 'child_process';
import webpack from 'webpack';
import config, { outputPath, outputFilename } from './webpack/webpack.config';
const compilerRunPromise = compiler =>
new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
if (stats && stats.hasErrors()) {
reject(err || stats.toString());
}
resolve(stats);
});
});
function onExit(childProcess) {
return new Promise((resolve, reject) => {
childProcess.once('exit', (code, signal) => {
if (code === 0) {
resolve(undefined);
} else {
reject(new Error('Exit with error code:' + code));
}
});
childProcess.once('error', err => {
reject(err);
});
});
}
const runProgram = async () => {
const outputFile = path.join(outputPath, outputFilename);
const program = spawn(process.execPath, [outputFile], {
stdio: [process.stdin, process.stdout, process.stderr],
std: 'inherit',
shell: true,
});
await onExit(program);
};
(async () => {
try {
const wpConfig = {
...config,
entry: path.join(__dirname, process.argv[2]),
};
const compiler = webpack(wpConfig);
await compilerRunPromise(compiler);
await runProgram();
} catch (err) {
// eslint-disable-next-line
console.log('err:', err);
process.exit(1);
}
process.exit(0);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment