Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active July 14, 2020 14:45
Show Gist options
  • Save sibelius/9595f381927b0a7097b3b587b946364f to your computer and use it in GitHub Desktop.
Save sibelius/9595f381927b0a7097b3b587b946364f to your computer and use it in GitHub Desktop.
run node files using webpack
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',
devtool: false,
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json', '.mjs'],
},
output: {
libraryTarget: 'commonjs2',
path: outputPath,
filename: outputFilename,
futureEmitAssets: true,
},
target: 'node',
externals: [
nodeExternals(),
nodeExternals({
modulesDir: path.resolve(__dirname, '../node_modules'),
whitelist: [/@app/],
}),
],
module: {
rules: [
{
test: /\.mjs$/,
type: 'javascript/auto',
},
{
test: /\.(js|jsx|ts|tsx)?$/,
use: {
loader: 'babel-loader?cacheDirectory',
},
exclude: [/node_modules/, path.resolve(__dirname, '.serverless'), 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);
});
});
const runProgram = () => {
const outputFile = path.join(outputPath, outputFilename);
const program = spawn(process.execPath, [outputFile], {
std: 'inherit',
shell: true,
});
program.stdout.on('data', (data) => {
// eslint-disable-next-line
console.log(data.toString());
});
program.stderr.on('data', (data) => {
// eslint-disable-next-line
console.log(data.toString());
});
program.on('exit', (code) => {
process.exit(code);
});
};
(async () => {
try {
const wpConfig = {
...config,
entry: path.join(__dirname, process.argv[2]),
};
const compiler = webpack(wpConfig);
await compilerRunPromise(compiler);
runProgram();
} catch (err) {
// eslint-disable-next-line
console.log('err: ', err);
process.exit(1);
}
process.exit(0);
})();
@sibelius
Copy link
Author

sibelius commented Apr 27, 2020

babel-node webpackx.js ./path/to/file.ts

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