Unverified Commit dea02ce9 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add event for webpack plugin customization (#76477)

Add an event for if webpack plugins customized or not. While
investigating adding this I found that when webpack config is added it
does not propagate the event data because the build workers are opted
out of. I've fixed that bug in this PR as it prohibited the new event
from working. I've added a test for both the found bug as well as the
newly added event.

- [x] Add event for webpack plugin customization
- [x] Fix reporting of features when webpack customization is added (bug
found while working on adding the event)
- [x] Add test for reporting features when webpack customization is
added

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent faae7019
......@@ -125,16 +125,29 @@ async function webpackBuildWithWorker(
return combinedResult
}
export function webpackBuild(
export async function webpackBuild(
withWorker: boolean,
compilerNames: typeof ORDERED_COMPILER_NAMES | null
): ReturnType<typeof webpackBuildWithWorker> {
if (withWorker) {
debug('using separate compiler workers')
return webpackBuildWithWorker(compilerNames)
return await webpackBuildWithWorker(compilerNames)
} else {
debug('building all compilers in same process')
const webpackBuildImpl = require('./impl').webpackBuildImpl
return webpackBuildImpl(null, null)
const curResult = await webpackBuildImpl(null, null)
// Mirror what happens in webpackBuildWithWorker
if (curResult.telemetryState) {
NextBuildContext.telemetryState = {
...curResult.telemetryState,
useCacheTracker: mergeUseCacheTrackers(
NextBuildContext.telemetryState?.useCacheTracker,
curResult.telemetryState.useCacheTracker
),
}
}
return curResult
}
}
......@@ -891,6 +891,40 @@ export default async function getBaseWebpackConfig(
return override || undefined
}
const telemetryPlugin =
!isRspack &&
!dev &&
isClient &&
new (
require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin')
).TelemetryPlugin(
new Map(
[
['swcLoader', useSWCLoader],
['swcRelay', !!config.compiler?.relay],
['swcStyledComponents', !!config.compiler?.styledComponents],
[
'swcReactRemoveProperties',
!!config.compiler?.reactRemoveProperties,
],
[
'swcExperimentalDecorators',
!!jsConfig?.compilerOptions?.experimentalDecorators,
],
['swcRemoveConsole', !!config.compiler?.removeConsole],
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
['swcEmotion', !!config.compiler?.emotion],
['transpilePackages', !!config.transpilePackages],
['skipMiddlewareUrlNormalize', !!config.skipMiddlewareUrlNormalize],
['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect],
['modularizeImports', !!config.modularizeImports],
// If esmExternals is not same as default value, it represents customized usage
['esmExternals', config.experimental.esmExternals !== true],
SWCBinaryTarget,
].filter<[Feature, boolean]>(Boolean as any)
)
)
let webpackConfig: webpack.Configuration = {
parallelism: getParallelism(),
...(isNodeServer ? { externalsPresets: { node: true } } : {}),
......@@ -2017,41 +2051,7 @@ export default async function getBaseWebpackConfig(
isClient &&
config.experimental.cssChunking &&
new CssChunkingPlugin(config.experimental.cssChunking === 'strict'),
!isRspack &&
!dev &&
isClient &&
new (
require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin')
).TelemetryPlugin(
new Map(
[
['swcLoader', useSWCLoader],
['swcRelay', !!config.compiler?.relay],
['swcStyledComponents', !!config.compiler?.styledComponents],
[
'swcReactRemoveProperties',
!!config.compiler?.reactRemoveProperties,
],
[
'swcExperimentalDecorators',
!!jsConfig?.compilerOptions?.experimentalDecorators,
],
['swcRemoveConsole', !!config.compiler?.removeConsole],
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
['swcEmotion', !!config.compiler?.emotion],
['transpilePackages', !!config.transpilePackages],
[
'skipMiddlewareUrlNormalize',
!!config.skipMiddlewareUrlNormalize,
],
['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect],
['modularizeImports', !!config.modularizeImports],
// If esmExternals is not same as default value, it represents customized usage
['esmExternals', config.experimental.esmExternals !== true],
SWCBinaryTarget,
].filter<[Feature, boolean]>(Boolean as any)
)
),
telemetryPlugin,
!isRspack &&
!dev &&
isNodeServer &&
......@@ -2357,6 +2357,8 @@ export default async function getBaseWebpackConfig(
let originalDevtool = webpackConfig.devtool
if (typeof config.webpack === 'function') {
const pluginCountBefore = webpackConfig.plugins?.length
webpackConfig = config.webpack(webpackConfig, {
dir,
dev,
......@@ -2373,6 +2375,14 @@ export default async function getBaseWebpackConfig(
: {}),
})
if (telemetryPlugin && pluginCountBefore) {
const pluginCountAfter = webpackConfig.plugins?.length
if (pluginCountAfter) {
const pluginsChanged = pluginCountAfter !== pluginCountBefore
telemetryPlugin.addUsage('webpackPlugins', pluginsChanged ? 1 : 0)
}
}
if (!webpackConfig) {
throw new Error(
`Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your ${config.configFileName}.\n` +
......
......@@ -48,6 +48,7 @@ export type Feature =
| 'skipTrailingSlashRedirect'
| 'modularizeImports'
| 'esmExternals'
| 'webpackPlugins'
| UseCacheTrackerKey
interface FeatureUsage {
featureName: Feature
......@@ -105,6 +106,7 @@ const BUILD_FEATURES: Array<Feature> = [
'skipTrailingSlashRedirect',
'modularizeImports',
'esmExternals',
'webpackPlugins',
]
export type TelemetryLoaderContext = {
......@@ -193,7 +195,17 @@ export class TelemetryPlugin implements webpack.WebpackPluginInstance {
}
}
apply(compiler: webpack.Compiler): void {
public addUsage(
featureName: Feature,
invocationCount: FeatureUsage['invocationCount']
): void {
this.usageTracker.set(featureName, {
featureName,
invocationCount,
})
}
public apply(compiler: webpack.Compiler): void {
compiler.hooks.make.tapAsync(
TelemetryPlugin.name,
async (compilation: webpack.Compilation, callback: () => void) => {
......@@ -238,15 +250,15 @@ export class TelemetryPlugin implements webpack.WebpackPluginInstance {
}
}
usages(): FeatureUsage[] {
public usages(): FeatureUsage[] {
return [...this.usageTracker.values()]
}
packagesUsedInServerSideProps(): string[] {
public packagesUsedInServerSideProps(): string[] {
return Array.from(eliminatedPackages)
}
getUseCacheTracker(): Record<UseCacheTrackerKey, number> {
public getUseCacheTracker(): Record<UseCacheTrackerKey, number> {
return Object.fromEntries(useCacheTracker)
}
}
......
......@@ -174,6 +174,7 @@ export type EventBuildFeatureUsage = {
| 'skipTrailingSlashRedirect'
| 'modularizeImports'
| 'esmExternals'
| 'webpackPlugins'
| UseCacheTrackerKey
invocationCount: number
}
......
module.exports = {
webpack(config) {
config.plugins.push(function MyPlugin() {
console.log('Custom webpack plugin loaded')
})
return config
},
}
......@@ -9,6 +9,7 @@ import {
killApp,
waitFor,
nextBuild,
findAllTelemetryEvents,
} from 'next-test-utils'
const appDir = path.join(__dirname, '..')
......@@ -355,6 +356,24 @@ describe('Telemetry CLI', () => {
expect(event).toMatch(/"buildTarget": "default"/)
expect(event).toMatch(/"hasWebpackConfig": true/)
expect(event).toMatch(/"hasBabelConfig": false/)
// This event doesn't get recorded for Turbopack as the webpack config is not executed.
if (!process.env.TURBOPACK) {
// Check if features are detected correctly when custom webpack config exists
const featureUsageEvents = findAllTelemetryEvents(
stderr,
'NEXT_BUILD_FEATURE_USAGE'
)
expect(featureUsageEvents).toContainEqual({
featureName: 'swcStyledComponents',
invocationCount: 0,
})
expect(featureUsageEvents).toContainEqual({
featureName: 'webpackPlugins',
invocationCount: 1,
})
}
})
it('detect static 404 correctly for `next build`', async () => {
const { stderr } = await nextBuild(appDir, [], {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment