Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade Webpack to version 5 #53

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,20 @@
"typescript": "^4.2.3"
},
"dependencies": {
"@babel/core": "^7.13.8",
"@babel/parser": "^7.13.9",
"@babel/plugin-proposal-export-default-from": "^7.12.13",
"@babel/traverse": "^7.13.0",
"@babel/core": "^7.18.13",
"@babel/parser": "^7.18.13",
"@babel/plugin-proposal-export-default-from": "^7.18.10",
"@babel/traverse": "^7.18.13",
"autoprefixer": "^9.7.6",
"babel-eslint": "^10.1.0",
"builtin-modules": "^3.1.0",
"css-loader": "^4.3.0",
"cssnano": "^4.1.10",
"csso-webpack-plugin": "^2.0.0-beta.1",
"debug": "^4.2.0",
"enhanced-resolve": "^5.7.0",
"esbuild": "^0.11.4",
"esbuild-loader": "^2.11.0",
"enhanced-resolve": "^5.10.0",
"esbuild": "^0.15.6",
"esbuild-loader": "^2.19.0",
"escape-string-regexp": "^2.0.0",
"fast-safe-stringify": "^2.0.7",
"file-loader": "^6.1.1",
Expand All @@ -96,15 +96,14 @@
"shebang-loader": "^0.0.1",
"shortid": "^2.2.15",
"stats-lite": "^2.1.0",
"string-replace-loader": "^3.0.1",
"string-replace-loader": "^3.1.0",
"svelte": "^3.35.0",
"svelte-loader": "^2.13.6",
"terser": "^5.6.0",
"terser-webpack-plugin": "^4.2.3",
"vm2": "^3.9.7",
"vue-loader": "^15.9.3",
"vue-template-compiler": "^2.6.12",
"webpack": "^4.44.2",
"vue": "^3.2.38",
"vue-loader": "^17.0.0",
"vue-template-compiler": "^2.7.10",
"webpack": "^5.74.0",
"write-file-webpack-plugin": "^4.5.1"
}
}
75 changes: 21 additions & 54 deletions src/config/makeWebpackConfig.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import autoprefixer from 'autoprefixer'
import TerserPlugin from 'terser-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import CssoWebpackPlugin from 'csso-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'

const log = require('debug')('bp:webpack')
import escapeRegex from 'escape-string-regexp'
import builtinModules from 'builtin-modules'
import webpack, { Entry } from 'webpack'
import { ESBuildMinifyPlugin } from 'esbuild-loader'
// @ts-ignore
import VueLoaderPlugin from 'vue-loader/lib/plugin'
import { VueLoaderPlugin } from 'vue-loader'

import { Externals } from '../common.types'

Expand All @@ -22,12 +19,7 @@ type MakeWebpackConfigOptions = {
minifier: 'esbuild' | 'terser'
}

type NodeBuiltIn = {
[key: string]: boolean | 'empty'
}

export default function makeWebpackConfig({
packageName,
entry,
externals,
debug,
Expand All @@ -44,23 +36,6 @@ export default function makeWebpackConfig({

log('external packages %o', externalsRegex)

const builtInNode: NodeBuiltIn = {}
builtinModules.forEach(mod => {
builtInNode[mod] = 'empty'
builtInNode[`node:${mod}`] = 'empty'
})

builtInNode['setImmediate'] = false
builtInNode['console'] = false
builtInNode['process'] = false
builtInNode['Buffer'] = false

// Don't mark an import as built in if it is the name of the package itself
// eg. `events`
if (builtInNode[packageName]) {
builtInNode[packageName] = false
}

// @ts-ignore
// @ts-ignore
// @ts-ignore
Expand All @@ -69,8 +44,8 @@ export default function makeWebpackConfig({
mode: 'production',
// bail: true,
optimization: {
namedChunks: true,
runtimeChunk: { name: 'runtime' },
chunkIds: 'named',
runtimeChunk: 'multiple',
minimize: true,
splitChunks: {
cacheGroups: {
Expand All @@ -85,17 +60,7 @@ export default function makeWebpackConfig({
// @ts-ignore: Appears that the library CssoWebpackPlugin might have incorrect definitions
minimizer: [
...(minifier === 'terser'
? [
new TerserPlugin({
parallel: true,
terserOptions: {
ie8: false,
output: {
comments: false,
},
},
}),
]
? ['...']
: [
new ESBuildMinifyPlugin({
target: 'esnext',
Expand All @@ -105,15 +70,15 @@ export default function makeWebpackConfig({
],
},
plugins: [
new webpack.IgnorePlugin(/^electron$/),
new webpack.IgnorePlugin({ resourceRegExp: /^electron$/ }),
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].bundle.css',
chunkFilename: '[id].bundle.css',
}),
...(debug ? [new WriteFilePlugin()] : []),
...(debug ? ([new WriteFilePlugin()] as any) : []),
],
resolve: {
modules: ['node_modules'],
Expand All @@ -129,10 +94,15 @@ export default function makeWebpackConfig({
'.sass',
'.scss',
],
mainFields: ['browser', 'module', 'main', 'style'],
mainFields: ['browser', 'import', 'module', 'main', 'style'],
conditionNames: ['browser', 'import', 'module', 'main', 'style'],
},
module: {
rules: [
{
test: /\.vue$/,
loader: require.resolve('vue-loader'),
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, require.resolve('css-loader')],
Expand All @@ -145,7 +115,7 @@ export default function makeWebpackConfig({
},
{
test: /\.js$/,
loader: [
use: [
// support CLI tools that start with a #!/usr/bin/node
require.resolve('shebang-loader'),
// ESBuild Minifier doesn't auto-remove license comments from code
Expand All @@ -172,13 +142,9 @@ export default function makeWebpackConfig({
},
},
},
{
test: /\.vue$/,
loader: require.resolve('vue-loader'),
},
{
test: /\.(scss|sass)$/,
loader: [
use: [
MiniCssExtractPlugin.loader,
require.resolve('css-loader'),
{
Expand All @@ -192,7 +158,7 @@ export default function makeWebpackConfig({
},
{
test: /\.less$/,
loader: [
use: [
MiniCssExtractPlugin.loader,
require.resolve('css-loader'),
{
Expand Down Expand Up @@ -229,14 +195,15 @@ export default function makeWebpackConfig({
},
],
},
node: builtInNode,
node: false,
output: {
filename: 'bundle.js',
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
pathinfo: false,
},
externals: (context, request, callback) =>
isExternalRequest(request)
? callback(null, 'commonjs ' + request)
externals: (context, callback) =>
context.request && isExternalRequest(context.request)
? callback(undefined, 'commonjs ' + context.request)
: callback(),
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/getDependencySizeTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ type StatsTree = {

async function bundleSizeTree(
packageName: string,
stats: webpack.Stats.ToJsonOutput,
stats: webpack.StatsCompilation,
minifier: 'terser' | 'esbuild'
) {
let startTime = performance.now()
Expand All @@ -138,21 +138,21 @@ async function bundleSizeTree(

// extract source path for each module
let modules: MakeModule[] = []
const makeModule = (mod: webpack.Stats.FnModules): MakeModule => {
const makeModule = (mod: webpack.StatsModule): MakeModule => {
// Uglifier cannot minify a json file, hence we need
// to make it valid javascript syntax
const isJSON = mod.identifier.endsWith('.json')
const isJSON = mod.identifier!.endsWith('.json')
const source = isJSON ? `$a$=${mod.source}` : mod.source

return {
path: modulePath(mod.identifier),
sources: [source || ''],
source: source || '',
path: modulePath(mod.identifier!),
sources: [(source as any) || ''],
source: (source as any) || '',
}
}

stats.modules
.filter(mod => !mod.name.startsWith('external'))
.filter(mod => !mod.name!.startsWith('external'))
.forEach(mod => {
if (mod.modules) {
mod.modules.forEach(subMod => {
Expand Down
30 changes: 20 additions & 10 deletions src/utils/build.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type BuildPackageArgs = {
options: BuildPackageOptions
}

type WebpackStatsAsset = NonNullable<webpack.Stats.ToJsonOutput['assets']>[0]
type WebpackStatsAsset = NonNullable<webpack.StatsCompilation['assets']>[0]

const BuildUtils = {
createEntryPoint(
Expand Down Expand Up @@ -116,7 +116,7 @@ const BuildUtils = {
compiler.run((err, stats) => {
const error = err as unknown as WebpackError // Webpack types incorrect
// stats object can be empty if there are build errors
resolve({ stats, error, memoryFileSystem })
resolve({ stats: stats as webpack.Stats, error, memoryFileSystem })

if (error) {
console.error(error)
Expand Down Expand Up @@ -187,11 +187,15 @@ const BuildUtils = {
return { assets: [] }
}
options.customImports.forEach(importt => {
entry[importt] = BuildUtils.createEntryPoint(name, installPath, {
customImports: [importt],
entryFilename: importt,
esm: true,
})
;(entry as any)[importt] = BuildUtils.createEntryPoint(
name,
installPath,
{
customImports: [importt],
entryFilename: importt,
esm: true,
}
)
})
} else {
entry['main'] = BuildUtils.createEntryPoint(name, installPath, {
Expand Down Expand Up @@ -223,7 +227,7 @@ const BuildUtils = {
errorDetails: false,
entrypoints: false,
reasons: false,
maxModules: 500,
chunkGroupMaxAssets: 500,
performance: false,
source: true,
depth: true,
Expand All @@ -245,7 +249,7 @@ const BuildUtils = {
throw new BuildError(error)
} else if (stats.compilation.errors && stats.compilation.errors.length) {
const missingModules = BuildUtils._parseMissingModules(
stats.compilation.errors
stats.compilation.errors as any
)

if (missingModules.length) {
Expand Down Expand Up @@ -306,8 +310,14 @@ const BuildUtils = {
}

const assetsGzipStartTime = performance.now()

const assetStats = jsonStats?.assets
?.filter(asset => !asset.chunkNames.includes('runtime'))
?.filter(
asset =>
!asset.chunkNames?.some(chunkName =>
(chunkName as string).startsWith('runtime~')
)
)
.filter(asset => !asset.name.endsWith('LICENSE.txt'))
.map(getAssetStats)
Telemetry.assetsGZIPParseTime(name, assetsGzipStartTime)
Expand Down
1 change: 1 addition & 0 deletions src/utils/exports.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ const resolver = enhancedResolve.create({
modules: webpackConfig?.resolve?.modules,
// @ts-ignore Error due to unsynced types for enhanced resolve and webpack
mainFields: webpackConfig?.resolve?.mainFields,
conditionNames: webpackConfig?.resolve?.conditionNames,
})

const resolve = async (context: string, path: string): Promise<string> =>
Expand Down
Loading