Skip to content

Instantly share code, notes, and snippets.

@dominics
Last active July 6, 2020 11:15
Show Gist options
  • Save dominics/f9f24430789d1b4c4f0297a31b5b3ff7 to your computer and use it in GitHub Desktop.
Save dominics/f9f24430789d1b4c4f0297a31b5b3ff7 to your computer and use it in GitHub Desktop.
Individual webpack stats per entrypoint
const path = require('path')
const slsw = require('serverless-webpack')
const { StatsWriterPlugin } = require('webpack-stats-plugin')
const yaml = require('js-yaml')
const fs = require('fs')
require('events').EventEmitter.defaultMaxListeners = 20 // default: 10, using 11 at the moment
/**
* slsw.lib.entries is used when invoking webpack from serverless, e.g. `serverless package`
* But it's not defined when invoking webpack independently, so we provide a fallback
*/
const entry =
slsw.lib.entries && Object.keys(slsw.lib.entries).length > 0
? slsw.lib.entries
: Object.assign(
...Object.values(yaml.load(fs.readFileSync(path.resolve(__dirname, 'serverless.yml'))).functions).map(
(f) => ({
[f.handler.split('.')[0]]: `./${f.handler.split('.')[0]}.ts`,
})
)
)
const isDev = slsw.lib.isLocal || process.env.LOCAL || process.env.NODE_ENV === 'development' // etc.
/**
* When packaging individually, serverless-webpack forms individual webpack configurations by
* deeply cloning this one, and adjusting the entrypoints. That means we can tell which function
* we are compiling, and vary the filename accurately.
*
* The returned path must be relative (to the output dir), not absolute.
*/
const statsFilename = (c) => `../stats/stats-${path.basename(c.entrypoints.entries().next().value[0])}.json`
module.exports = {
context: process.cwd(),
mode: isDev ? 'development' : 'production',
devtool: isDev ? 'inline-source-map' : 'none',
entry,
externals: ['aws-sdk', 'pino-pretty', 'pino-debug', 'debug', 'pg'],
resolve: {
extensions: ['.ts', '.js'],
},
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, '.webpack'),
filename: '[name].js',
},
target: 'node',
module: {
rules: [
{
// Include ts, tsx files.
test: /\.tsx?$/,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true, // typechecking is through tsc --noEmit
experimentalWatchApi: true,
},
},
],
},
],
},
plugins: [].concat(
process.env.WEBPACK_STATS
? [
new StatsWriterPlugin({
filename: statsFilename,
fields: null,
stats: {
maxModules: Infinity,
source: false,
},
}),
]
: []
),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment