I'm trying to use code splitting so I can unit-test production code without duplicating modules. I would like webpack to recognize that my *.test.ts files rely on the same modules as the source code itself, and output a bundle containing those shared dependencies. However, webpack only outputs bundles corresponding to the entry points and does not extract the shared code into its own bundle.
I'm using the basic configuration provided in the official documentation for my use case (https://webpack.js.org/guides/code-splitting#prevent-duplication), but no luck. The only substantial difference I can see is that I'm using loaders to transpile my code, and the official examples aren't.
Folder structure
|- /MyProject
|- webpack.config.js
|- /node_modules
|- /build
|- /src
|- webServer.ts
|- myLib.ts
|- webServer.test.ts
|- myLib.test.ts
webServer.ts
import './myLib';
// do webserver stuff
myLib.test.ts
import './myLib';
import mocha, chai, etc etc
// unit tests for myLib
webServer.test.ts
import './myLib.test';
// this file is just a convenient entry point for grouping unit tests
webpack.config.js
var nodeExternals = require('webpack-node-externals');
const serverConfig = {
mode: 'development',
target: 'node',
externals: [nodeExternals()],
entry: {
webServer: './src/webServer.ts',
'webServer.test': './src/webServer.test.ts'
},
output: {
path: __dirname + '/build',
filename: '[name].js'
},
resolve: {
extensions: ['.ts']
},
optimization: {
splitChunks: {
chunks: 'all',
}
},
module: {
rules: [{
test: /\.ts/,
include: [__dirname],
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{ loader: 'ts-loader' }
]
}]
}
module.exports = [serverConfig];
I expect webpack to emit 3 files: webServer.js
, webServer.test.js
, and a third that bundles myLib
. However, I only get 2 files: webServer.js
and webServer.test.js