We are trying to chunk specific files using webpack's optimization.splitChunks.cacheGroups
feature but when we do the library that we have defined in the output is always undefined.
If we remove the cacheGroups object we are able to access window.foo
Locally we use the HTMLWebpackPlugin to inject all the required chunks into index.html sequentially so everything works.
However in production we use dynamic pages and only add only our bundled client.js
file to the page. This file doesn't call the generated chunks that we assumed that it should. We have other cacheGroups as well but thought I'd just use vendors for simplicity.
I have been trying out many of the different optimization configurations with no progress, I've also found a few others with this problem but no real viable solutions or examples with how it was solved, so I am reaching out here:
Is there a basic configuration step that I am missing so that window.foo
will not equal undefined
?
If this is not possible do I need to import the generated chunks into the main client.js
file somehow? Note: I've tried referencing them from dist put can never resolve the path?
Thanks for any help you can provide.
const webpack = require('webpack')
const path = require('path')
// Webpack plugins
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// Directories
const DEV_DIR = path.resolve(__dirname, '../src')
const PROD_DIR = path.resolve(__dirname, '../dist')
const CYPRESS_DIR = path.resolve(__dirname, '../cypress')
module.exports = {
context: DEV_DIR,
entry: { client: './js/client/client.js' },
output: {
path: PROD_DIR,
filename: 'js/[name].js',
chunkFilename: 'js/[name].[contenthash].js',
clean: true,
library: {
name: 'foo',
type: 'var'
}
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 0,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor'
}
}
}
},
module: {
rules:
[
{
test: /\.js$/,
exclude: [
/node_modules/,
CYPRESS_DIR
],
loader: 'babel-loader',
options: { plugins: ['lodash'] }
}
]
},
plugins: [
new LodashModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: 'html/global.html',
filename: 'index.html',
inject: false
}),
],
resolve: {
extensions: ['.js', '.vue', '.json']
}
}