diff --git a/packages/cli/src/lib/bundle/config.ts b/packages/cli/src/lib/bundle/config.ts index 11b9e7aa2f..2d39570339 100644 --- a/packages/cli/src/lib/bundle/config.ts +++ b/packages/cli/src/lib/bundle/config.ts @@ -20,6 +20,7 @@ import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; import ModuleScopePlugin from 'react-dev-utils/ModuleScopePlugin'; import { BundlingPaths } from './paths'; import { loaders } from './loaders'; +import { optimization } from './optimization'; // import checkRequiredFiles from 'react-dev-utils/checkRequiredFiles'; // import ModuleNotFoundPlugin from 'react-dev-utils/ModuleNotFoundPlugin'; // import errorOverlayMiddleware from 'react-dev-utils/errorOverlayMiddleware'; @@ -60,6 +61,7 @@ export function createConfig(options: BundlingOptions): webpack.Configuration { publicPath: '/', filename: 'bundle.js', }, + optimization: optimization(), plugins: [ new HtmlWebpackPlugin({ template: paths.targetHtml, diff --git a/packages/cli/src/lib/bundle/optimization.ts b/packages/cli/src/lib/bundle/optimization.ts new file mode 100644 index 0000000000..89679c8026 --- /dev/null +++ b/packages/cli/src/lib/bundle/optimization.ts @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Options } from 'webpack'; + +export const optimization = (): Options.Optimization => { + return { + runtimeChunk: 'single', + splitChunks: { + automaticNameDelimiter: '-', + cacheGroups: { + default: false, + // Put all vendor code needed for initial page load in individual files if they're big + // enough, if they're smaller they end up in the main + packages: { + chunks: 'initial', + test: /[\\/]node_modules[\\/]/, + name(module: any) { + // get the name. E.g. node_modules/packageName/not/this/part.js + // or node_modules/packageName + const packageName = module.context.match( + /[\\/]node_modules[\\/](.*?)([\\/]|$)/, + )[1]; + + // npm package names are URL-safe, but some servers don't like @ symbols + return packageName.replace('@', ''); + }, + filename: 'module-[name].[chunkhash:8].js', + priority: 10, + minSize: 100000, + minChunks: 1, + maxAsyncRequests: Infinity, + maxInitialRequests: Infinity, + } as any, // filename is not included in type, but we need it + // Group together the smallest modules + vendor: { + chunks: 'initial', + test: /[\\/]node_modules[\\/]/, + name: 'vendor', + priority: 5, + enforce: true, + }, + }, + }, + }; +};