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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[legacy-framework] Fix webpack 5 support (Webpack 5 now used by default) (patch) #2453

Merged
merged 13 commits into from
Jun 8, 2021
Merged
Show file tree
Hide file tree
Changes from 9 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
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ bin
packages/generator/templates/**
.github/ISSUE_TEMPLATE/bug_report.md
nextjs/packages/next/compiled/**

// Because file from nextjs upstream isn't formatted properly
nextjs/packages/next/build/webpack-config.ts
3 changes: 3 additions & 0 deletions nextjs/.prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ packages/next-codemod/**/*.js
packages/next-codemod/**/*.d.ts
packages/next-env/**/*.d.ts
test-timings.json

// Because file from nextjs upstream isn't formatted properly
nextjs/packages/next/build/webpack-config.ts
192 changes: 114 additions & 78 deletions nextjs/packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ import WebpackConformancePlugin, {
} from './webpack/plugins/webpack-conformance-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'

import fs from 'fs'
import { getProjectRoot } from '../server/lib/utils'

/* ------ Blitz.js ------- */
function doesDbModuleExist() {
const projectRoot = getProjectRoot()
return (
fs.existsSync(path.join(projectRoot, 'db/index.js')) ||
fs.existsSync(path.join(projectRoot, 'db/index.ts')) ||
fs.existsSync(path.join(projectRoot, 'db/index.tsx'))
)
}
/* ------ Blitz.js ------- */

type ExcludesFalse = <T>(x: T | false) => x is T

const devtoolRevertWarning = execOnce(
Expand Down Expand Up @@ -882,6 +896,9 @@ export default async function getBaseWebpackConfig(
entry: async () => {
return {
...(clientEntries ? clientEntries : {}),
...(isServer && doesDbModuleExist()
? { 'blitz-db': './db/index' }
: {}),
...entrypoints,
}
},
Expand Down Expand Up @@ -997,6 +1014,24 @@ export default async function getBaseWebpackConfig(
]
: defaultLoaders.babel,
},
...(isServer
? []
: [
{
issuer: /(mutations|queries)(?!.*\.client)/,
resource: /_resolvers/,
use: { loader: require.resolve('null-loader') },
},
// Because of packages/core/src/prisma-utils.ts
{
test: /[\\/]npm-which[\\/]/,
use: { loader: require.resolve('null-loader') },
},
{
test: /[\\/]cross-spawn[\\/]/,
use: { loader: require.resolve('null-loader') },
},
]),
].filter(Boolean),
},
plugins: [
Expand Down Expand Up @@ -1556,93 +1591,94 @@ export default async function getBaseWebpackConfig(

// Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
;[].forEach.call(webpackConfig.module.rules, function (
rule: webpack.RuleSetRule
) {
if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
return
}

const isSass =
rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
const isLess = rule.test.source === '\\.less$'
const isCss = rule.test.source === '\\.css$'
const isStylus = rule.test.source === '\\.styl$'
;[].forEach.call(
webpackConfig.module.rules,
function (rule: webpack.RuleSetRule) {
if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
return
}

// Check if the rule we're iterating over applies to Sass, Less, or CSS
if (!(isSass || isLess || isCss || isStylus)) {
return
}
const isSass =
rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
const isLess = rule.test.source === '\\.less$'
const isCss = rule.test.source === '\\.css$'
const isStylus = rule.test.source === '\\.styl$'

;[].forEach.call(rule.use, function (use: webpack.RuleSetUseItem) {
if (
!(
use &&
typeof use === 'object' &&
// Identify use statements only pertaining to `css-loader`
(use.loader === 'css-loader' ||
use.loader === 'css-loader/locals') &&
use.options &&
typeof use.options === 'object' &&
// The `minimize` property is a good heuristic that we need to
// perform this hack. The `minimize` property was only valid on
// old `css-loader` versions. Custom setups (that aren't next-sass,
// next-less or next-stylus) likely have the newer version.
// We still handle this gracefully below.
(Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
Object.prototype.hasOwnProperty.call(
use.options,
'exportOnlyLocals'
))
)
) {
// Check if the rule we're iterating over applies to Sass, Less, or CSS
if (!(isSass || isLess || isCss || isStylus)) {
return
}

// Try to monkey patch within a try-catch. We shouldn't fail the build
// if we cannot pull this off.
// The user may not even be using the `next-sass` or `next-less` or
// `next-stylus` plugins.
// If it does work, great!
try {
// Resolve the version of `@zeit/next-css` as depended on by the Sass,
// Less or Stylus plugin.
const correctNextCss = require.resolve('@zeit/next-css', {
paths: [
isCss
? // Resolve `@zeit/next-css` from the base directory
dir
: // Else, resolve it from the specific plugins
require.resolve(
isSass
? '@zeit/next-sass'
: isLess
? '@zeit/next-less'
: isStylus
? '@zeit/next-stylus'
: 'next'
),
],
})
;[].forEach.call(rule.use, function (use: webpack.RuleSetUseItem) {
if (
!(
use &&
typeof use === 'object' &&
// Identify use statements only pertaining to `css-loader`
(use.loader === 'css-loader' ||
use.loader === 'css-loader/locals') &&
use.options &&
typeof use.options === 'object' &&
// The `minimize` property is a good heuristic that we need to
// perform this hack. The `minimize` property was only valid on
// old `css-loader` versions. Custom setups (that aren't next-sass,
// next-less or next-stylus) likely have the newer version.
// We still handle this gracefully below.
(Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
Object.prototype.hasOwnProperty.call(
use.options,
'exportOnlyLocals'
))
)
) {
return
}

// If we found `@zeit/next-css` ...
if (correctNextCss) {
// ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your
// `node_modules` tree.
const correctCssLoader = require.resolve(use.loader, {
paths: [correctNextCss],
// Try to monkey patch within a try-catch. We shouldn't fail the build
// if we cannot pull this off.
// The user may not even be using the `next-sass` or `next-less` or
// `next-stylus` plugins.
// If it does work, great!
try {
// Resolve the version of `@zeit/next-css` as depended on by the Sass,
// Less or Stylus plugin.
const correctNextCss = require.resolve('@zeit/next-css', {
paths: [
isCss
? // Resolve `@zeit/next-css` from the base directory
dir
: // Else, resolve it from the specific plugins
require.resolve(
isSass
? '@zeit/next-sass'
: isLess
? '@zeit/next-less'
: isStylus
? '@zeit/next-stylus'
: 'next'
),
],
})
if (correctCssLoader) {
// We saved the user from a failed build!
use.loader = correctCssLoader

// If we found `@zeit/next-css` ...
if (correctNextCss) {
// ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your
// `node_modules` tree.
const correctCssLoader = require.resolve(use.loader, {
paths: [correctNextCss],
})
if (correctCssLoader) {
// We saved the user from a failed build!
use.loader = correctCssLoader
}
}
} catch (_) {
// The error is not required to be handled.
}
} catch (_) {
// The error is not required to be handled.
}
})
})
})
}
)
}

// Backwards compat for `main.js` entry key
Expand Down
2 changes: 1 addition & 1 deletion nextjs/packages/next/next-server/server/config-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export const defaultConfig: NextConfig = {
serialWebpackBuild: false,
turboMode: false,
eslint: false,
reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0,
reactRoot: true,
enableBlurryPlaceholder: false,
disableOptimizedLoading: true,
gzipSize: true,
Expand Down
17 changes: 17 additions & 0 deletions nextjs/packages/next/server/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import fs from 'fs'
import path from 'path'

export function printAndExit(message: string, code = 1) {
if (code === 0) {
console.log(message)
Expand All @@ -12,3 +15,17 @@ export function getNodeOptionsWithoutInspect() {
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/
return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '')
}

export function getProjectRoot() {
return path.dirname(getConfigSrcPath())
}

export function getConfigSrcPath() {
const tsPath = path.resolve(path.join(process.cwd(), 'blitz.config.ts'))
if (fs.existsSync(tsPath)) {
return tsPath
} else {
const jsPath = path.resolve(path.join(process.cwd(), 'blitz.config.js'))
return jsPath
}
}
4 changes: 2 additions & 2 deletions nextjs/test/integration/build-output/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad)).toBeCloseTo(gz ? 69.5 : 215, 1)
expect(err404FirstLoad.endsWith('kB')).toBe(true)

expect(parseFloat(sharedByAll)).toBeCloseTo(gz ? 66.4 : 206, 1)
expect(parseFloat(sharedByAll)).toBeCloseTo(gz ? 66.5 : 206, 1)
expect(sharedByAll.endsWith('kB')).toBe(true)

const appSizeValue = _appSize.endsWith('kB')
Expand All @@ -149,7 +149,7 @@ describe('Build Output', () => {
true
)

expect(parseFloat(mainSize)).toBeCloseTo(gz ? 19.5 : 60.6, 1)
expect(parseFloat(mainSize)).toBeCloseTo(gz ? 19.6 : 60.7, 1)
expect(mainSize.endsWith('kB')).toBe(true)

expect(parseFloat(frameworkSize)).toBeCloseTo(gz ? 44.9 : 142, 1)
Expand Down
2 changes: 1 addition & 1 deletion nextjs/test/integration/size-limit/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,6 @@ describe('Production response size', () => {
const delta = responseSizesBytes / 1024

// Expected difference: < 0.5
expect(delta).toBeCloseTo(298, 0)
expect(delta).toBeCloseTo(298.6, 0)
})
})
1 change: 1 addition & 0 deletions packages/config/index-browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {}
4 changes: 3 additions & 1 deletion packages/config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
"test": "jest --passWithNoTests",
"test:watch": "jest --watch"
},
"browser": "index-browser.js",
"main": "dist/blitzjs-config.cjs.js",
"module": "dist/blitzjs-config.esm.js",
"types": "dist/blitzjs-config.cjs.d.ts",
"files": [
"dist"
"dist",
"index-browser.js"
],
"keywords": [
"next.config.js",
Expand Down
4 changes: 4 additions & 0 deletions packages/config/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,14 @@ export interface BlitzConfigNormalized extends BlitzConfig {
}

export function getProjectRoot() {
// TODO consolidate with nextjs/packages/next/server/lib/utils.ts
// IF THIS IS UPDATED, so does the one inside nextjs
return path.dirname(getConfigSrcPath())
}

export function getConfigSrcPath() {
// TODO consolidate with nextjs/packages/next/server/lib/utils.ts
// IF THIS IS UPDATED, so does the one inside nextjs
const tsPath = path.resolve(path.join(process.cwd(), "blitz.config.ts"))
if (existsSync(tsPath)) {
return tsPath
Expand Down
6 changes: 2 additions & 4 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
"head.ts",
"image.ts",
"index.ts",
"server/index.ts",
"with-blitz.ts"
"server/index.ts"
]
},
"main": "dist/blitzjs-core.cjs.js",
Expand All @@ -31,8 +30,7 @@
"dynamic",
"head",
"image",
"server",
"with-blitz"
"server"
],
"dependencies": {
"@blitzjs/config": "0.36.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/auth/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ process.nextTick(getConfig)

const getDb = () => {
const projectRoot = getProjectRoot()
const path = join(projectRoot, ".next/blitz/db.js")
const path = join(projectRoot, ".next/server/blitz-db.js")
// eslint-disable-next-line no-eval -- block webpack from following this module path
return eval("require")(path).default
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const fixNodeFileTrace = () => {
const path = require("path")
path.resolve("next.config.js")
path.resolve(".blitz/blitz.config.js")
path.resolve(".next/blitz/db.js")
path.resolve(".next/server/blitz-db.js")
}
export const withFixNodeFileTrace = (fn: Function) => {
fixNodeFileTrace()
Expand Down
Loading