Skip to content

Commit

Permalink
Add initial changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Dec 20, 2024
1 parent 5e0079e commit 989dd90
Show file tree
Hide file tree
Showing 24 changed files with 556 additions and 68 deletions.
3 changes: 3 additions & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@
"sharp": "^0.33.5"
},
"devDependencies": {
"enhanced-resolve": "5.17.1",
"@rspack/core": "1.1.8",
"@rspack/plugin-react-refresh": "1.0.1",
"@ampproject/toolbox-optimizer": "2.8.3",
"@babel/code-frame": "7.22.5",
"@babel/core": "7.22.5",
Expand Down
6 changes: 6 additions & 0 deletions packages/next/src/bin/next.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#!/usr/bin/env node

if (process.env.NEXT_RSPACK) {
console.log('next bin rspack')
// silent rspack's schema check
process.env.RSPACK_CONFIG_VALIDATE = 'loose-silent'
}

import '../server/require-hook'

import { Argument, Command, Option } from 'next/dist/compiled/commander'
Expand Down
6 changes: 4 additions & 2 deletions packages/next/src/build/babel/loader/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Span } from '../../../trace'
import { Span } from '../../../trace'
import transform from './transform'
import type { NextJsLoaderContext } from './types'

Expand Down Expand Up @@ -49,7 +49,9 @@ const nextBabelLoaderOuter = function nextBabelLoaderOuter(
) {
const callback = this.async()

const loaderSpan = this.currentTraceSpan.traceChild('next-babel-turbo-loader')
const loaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('next-babel-turbo-loader')
loaderSpan
.traceAsyncFn(() =>
nextBabelLoader.call(this, loaderSpan, inputSource, inputSourceMap)
Expand Down
12 changes: 11 additions & 1 deletion packages/next/src/build/handle-externals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export async function resolveExternal(
baseEsmResolveOptions: any = NODE_BASE_ESM_RESOLVE_OPTIONS,
baseResolveOptions: any = NODE_BASE_RESOLVE_OPTIONS
) {
const isRspack = Boolean(process.env.NEXT_RSPACK)
const esmExternals = !!esmExternalsConfig
const looseEsmExternals = esmExternalsConfig === 'loose'

Expand All @@ -74,7 +75,16 @@ export async function resolveExternal(
for (const preferEsm of preferEsmOptions) {
const resolveOptions = preferEsm ? esmResolveOptions : nodeResolveOptions

const resolve = getResolve(resolveOptions)
let resolve: ReturnType<typeof getResolve>

// RSPack doesn't support getResolve yet
if (isRspack) {
// eslint-disable-next-line
const { ResolverFactory } = require('enhanced-resolve')
resolve = ResolverFactory.createResolver(resolveOptions)
} else {
resolve = getResolve(resolveOptions)
}

// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
Expand Down
90 changes: 60 additions & 30 deletions packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,8 @@ export default async function getBaseWebpackConfig(
const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
const isNodeServer = compilerType === COMPILER_NAMES.server

const isRspack = Boolean(process.env.NEXT_RSPACK)

// If the current compilation is aimed at server-side code instead of client-side code.
const isNodeOrEdgeCompilation = isNodeServer || isEdgeServer

Expand Down Expand Up @@ -706,6 +708,14 @@ export default async function getBaseWebpackConfig(
plugins: [
isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined,
].filter(Boolean) as webpack.ResolvePluginInstance[],

...((isRspack
? {
// tsConfig: {
// configFile: ,
// },
}
: {}) as any),
}

// Packages which will be split into the 'framework' chunk.
Expand Down Expand Up @@ -983,7 +993,8 @@ export default async function getBaseWebpackConfig(
}): boolean {
return (
!module.type?.startsWith('css') &&
module.size() > 160000 &&
// RSPack doesn't support module.size
(isRspack || module.size() > 160000) &&
/node_modules[/\\]/.test(module.nameForCondition() || '')
)
},
Expand All @@ -997,12 +1008,15 @@ export default async function getBaseWebpackConfig(
if (isModuleCSS(module)) {
module.updateHash(hash)
} else {
if (!module.libIdent) {
throw new Error(
`Encountered unknown module type: ${module.type}. Please open an issue.`
)
// RSPack doesn't support this
if (!isRspack) {
if (!module.libIdent) {
throw new Error(
`Encountered unknown module type: ${module.type}. Please open an issue.`
)
}
hash.update(module.libIdent({ context: dir }))
}
hash.update(module.libIdent({ context: dir }))
}

// Ensures the name of the chunk is not the same between two modules in different layers
Expand Down Expand Up @@ -1047,28 +1061,34 @@ export default async function getBaseWebpackConfig(
minimizer: [
// Minify JavaScript
(compiler: webpack.Compiler) => {
// @ts-ignore No typings yet
const { MinifyPlugin } =
require('./webpack/plugins/minify-webpack-plugin/src/index.js') as typeof import('./webpack/plugins/minify-webpack-plugin/src')
new MinifyPlugin().apply(compiler)
// use built-in minimizer for RSPack
if (!isRspack) {
// @ts-ignore No typings yet
const { MinifyPlugin } =
require('./webpack/plugins/minify-webpack-plugin/src/index.js') as typeof import('./webpack/plugins/minify-webpack-plugin/src')
new MinifyPlugin().apply(compiler)
}
},
// Minify CSS
(compiler: webpack.Compiler) => {
const {
CssMinimizerPlugin,
} = require('./webpack/plugins/css-minimizer-plugin')
new CssMinimizerPlugin({
postcssOptions: {
map: {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline: false,
// `annotation: false` skips appending the `sourceMappingURL`
// to the end of the CSS file. Webpack already handles this.
annotation: false,
// us RSPack handling
if (!isRspack) {
const {
CssMinimizerPlugin,
} = require('./webpack/plugins/css-minimizer-plugin')
new CssMinimizerPlugin({
postcssOptions: {
map: {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline: false,
// `annotation: false` skips appending the `sourceMappingURL`
// to the end of the CSS file. Webpack already handles this.
annotation: false,
},
},
},
}).apply(compiler)
}).apply(compiler)
}
},
],
},
Expand Down Expand Up @@ -1731,7 +1751,12 @@ export default async function getBaseWebpackConfig(
}
),
dev && new MemoryWithGcCachePlugin({ maxGenerations: 5 }),
dev && isClient && new ReactRefreshWebpackPlugin(webpack),
dev &&
isClient &&
(isRspack
? // eslint-disable-next-line
new (require('@rspack/plugin-react-refresh') as any)()
: new ReactRefreshWebpackPlugin(webpack)),
// Makes sure `Buffer` and `process` are polyfilled in client and flight bundles (same behavior as webpack 4)
(isClient || isEdgeServer) &&
new webpack.ProvidePlugin({
Expand Down Expand Up @@ -1761,8 +1786,11 @@ export default async function getBaseWebpackConfig(
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev,
}),
(isClient || isEdgeServer) && new DropClientPage(),
isNodeServer &&
// RSPack doesn't support the parser hooks used here
!isRspack && (isClient || isEdgeServer) && new DropClientPage(),
// RSPack doesn't support all APIs we need for tracing via plugin
!isRspack &&
isNodeServer &&
!dev &&
new (require('./webpack/plugins/next-trace-entrypoints-plugin')
.TraceEntryPointsPlugin as typeof import('./webpack/plugins/next-trace-entrypoints-plugin').TraceEntryPointsPlugin)(
Expand Down Expand Up @@ -1840,7 +1868,7 @@ export default async function getBaseWebpackConfig(
appDirEnabled: hasAppDir,
clientRouterFilters,
}),
new ProfilingPlugin({ runWebpackSpan, rootDir: dir }),
!isRspack && new ProfilingPlugin({ runWebpackSpan, rootDir: dir }),
new WellKnownErrorsPlugin(),
isClient &&
new CopyFilePlugin({
Expand Down Expand Up @@ -1891,11 +1919,13 @@ export default async function getBaseWebpackConfig(
new NextFontManifestPlugin({
appDir,
}),
!dev &&
!isRspack &&
!dev &&
isClient &&
config.experimental.cssChunking &&
new CssChunkingPlugin(config.experimental.cssChunking === 'strict'),
!dev &&
!isRspack &&
!dev &&
isClient &&
new (require('./webpack/plugins/telemetry-plugin').TelemetryPlugin)(
new Map(
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/build/webpack/config/blocks/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const base = curry(function base(
shouldIgnorePath,
})
)
} else if (config.devtool === 'eval-source-map') {
} else if (config.devtool === 'eval-source-map' && !process.env.NEXT_RSPACK) {
// We're using a fork of `eval-source-map`
config.devtool = false
config.plugins.push(
Expand Down
10 changes: 8 additions & 2 deletions packages/next/src/build/webpack/config/blocks/css/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export const css = curry(async function css(
ctx: ConfigurationContext,
config: webpack.Configuration
) {
const isRspack = Boolean(process.env.NEXT_RSPACK)
const {
prependData: sassPrependData,
additionalData: sassAdditionalData,
Expand Down Expand Up @@ -576,6 +577,8 @@ export const css = curry(async function css(
// Exclude extensions that webpack handles by default
exclude: [
/\.(js|mjs|jsx|ts|tsx)$/,
// TODO investigate why this is needed
...(isRspack ? [/^$/] : []),
/\.html$/,
/\.json$/,
/\.webpack\[[^\]]+\]$/,
Expand All @@ -592,8 +595,11 @@ export const css = curry(async function css(
// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.hasAppDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin =
require('../../../plugins/mini-css-extract-plugin').default
const MiniCssExtractPlugin = isRspack
? // eslint-disable-next-line
require('@rspack/core').CssExtractRspackPlugin
: require('../../../plugins/mini-css-extract-plugin').default

fns.push(
plugin(
// @ts-ignore webpack 5 compat
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function getClientStyleLoader({
isDevelopment: boolean
assetPrefix: string
}): webpack.RuleSetUseItem {
const isRspack = Boolean(process.env.NEXT_RSPACK)
const shouldEnableApp = typeof isAppDir === 'boolean' ? isAppDir : hasAppDir

// Keep next-style-loader for development mode in `pages/`
Expand Down Expand Up @@ -41,8 +42,11 @@ export function getClientStyleLoader({
}
}

const MiniCssExtractPlugin =
require('../../../../plugins/mini-css-extract-plugin').default
const MiniCssExtractPlugin = isRspack
? // eslint-disable-next-line
require('@rspack/core').rspack.CssExtractRspackPlugin.loader
: require('../../../../plugins/mini-css-extract-plugin').default

return {
loader: MiniCssExtractPlugin.loader,
options: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import CssSyntaxError from './CssSyntaxError'
import Warning from '../../postcss-loader/src/Warning'
import { stringifyRequest } from '../../../stringify-request'
import { Span } from '../../../../../trace'

const moduleRegExp = /\.module\.\w+$/i

Expand Down Expand Up @@ -142,7 +143,9 @@ export default async function loader(
const plugins: any[] = []
const callback = this.async()

const loaderSpan = this.currentTraceSpan.traceChild('css-loader')
const loaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('css-loader')

loaderSpan
.traceAsyncFn(async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Span } from '../../../trace'
import { stringifyRequest } from '../stringify-request'

export type ClientPagesLoaderOptions = {
Expand All @@ -7,9 +8,9 @@ export type ClientPagesLoaderOptions = {

// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
function nextClientPagesLoader(this: any) {
const pagesLoaderSpan = this.currentTraceSpan.traceChild(
'next-client-pages-loader'
)
const pagesLoaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('next-client-pages-loader')

return pagesLoaderSpan.traceFn(() => {
const { absolutePagePath, page } =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { bold, cyan } from '../../../../lib/picocolors'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import postcssNextFontPlugin from './postcss-next-font'
import { promisify } from 'util'
import { Span } from '../../../../trace'

export default async function nextFontLoader(this: any) {
const nextFontLoaderSpan =
this.currentTraceSpan.traceChild('next-font-loader')
const nextFontLoaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('next-font-loader')
return nextFontLoaderSpan.traceAsyncFn(async () => {
const callback = this.async()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../../server/image-optimizer'
import { getBlurImage } from './blur'
import { Span } from '../../../../trace'

interface Options {
compilerType: CompilerNameValues
Expand All @@ -13,7 +14,9 @@ interface Options {
}

function nextImageLoader(this: any, content: Buffer) {
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')
const imageLoaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('next-image-loader')
return imageLoaderSpan.traceAsyncFn(async () => {
const options: Options = this.getOptions()
const { compilerType, isDev, assetPrefix, basePath } = options
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import path from 'path'
import { stringifyRequest } from '../../stringify-request'
import { Span } from '../../../../trace'

const loaderApi = () => {}

loaderApi.pitch = function loader(this: any, request: any): any {
const loaderSpan = this.currentTraceSpan.traceChild('next-style-loader')
const loaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('next-style-loader')

return loaderSpan.traceFn(() => {
const options = this.getOptions()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Warning from './Warning'
import SyntaxError from './Error'
import { normalizeSourceMap, normalizeSourceMapAfterPostcss } from './utils'
import { Span } from '../../../../../trace'

/**
* **PostCSS Loader**
Expand All @@ -15,7 +16,9 @@ export default async function loader(
sourceMap: any,
meta: any
): Promise<void> {
const loaderSpan = this.currentTraceSpan.traceChild('postcss-loader')
const loaderSpan = (
this.currentTraceSpan || new Span({ name: '' })
).traceChild('postcss-loader')
const callback = this.async()

loaderSpan
Expand Down
Loading

0 comments on commit 989dd90

Please sign in to comment.