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 12 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
16 changes: 8 additions & 8 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ jobs:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
**/node_modules
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v9-${{ hashFiles('yarn.lock') }}
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v10-${{ hashFiles('yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ runner.node_version}}-yarn-v9-
${{ runner.os }}-${{ runner.node_version}}-yarn-v10-
- name: Install dependencies
run: yarn install --frozen-lockfile --silent
env:
Expand Down Expand Up @@ -72,9 +72,9 @@ jobs:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
**/node_modules
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v9-${{ hashFiles('yarn.lock') }}
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v10-${{ hashFiles('yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ runner.node_version}}-yarn-v9-
${{ runner.os }}-${{ runner.node_version}}-yarn-v10-
- run: yarn install --frozen-lockfile --check-files
- name: Build Packages
run: yarn build
Expand Down Expand Up @@ -140,9 +140,9 @@ jobs:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
**/node_modules
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v9-${{ hashFiles('yarn.lock') }}
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v10-${{ hashFiles('yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ runner.node_version}}-yarn-v9-
${{ runner.os }}-${{ runner.node_version}}-yarn-v10-
- run: yarn install --frozen-lockfile --check-files
# - run: yarn cpy node_modules/.blitz packages/core/node_modules/.blitz
# if: matrix.os == 'windows-latest'
Expand Down Expand Up @@ -375,9 +375,9 @@ jobs:
**/node_modules
/home/runner/.cache/Cypress
C:\Users\runneradmin\AppData\Local\Cypress\Cache
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v9-${{ hashFiles('yarn.lock') }}
key: ${{ runner.os }}-${{ runner.node_version}}-yarn-v10-${{ hashFiles('yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ runner.node_version}}-yarn-v9-
${{ runner.os }}-${{ runner.node_version}}-yarn-v10-

- run: yarn install --check-files
if: ${{ steps.docs-change.outputs.DOCS_CHANGE != 'docs only change' }}
Expand Down
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
9 changes: 8 additions & 1 deletion examples/store/app/products/pages/products/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import {Link, BlitzPage, InferGetStaticPropsType} from "blitz"
import getProducts, {averagePrice} from "../../queries/getProducts"
import getProducts from "../../queries/getProducts"
import {sum} from "lodash"
import {Product} from "@prisma/client"

// regression test for #1646
import {getMeSomeQualityHumor} from "../../api"
console.log("Attention! Must read: " + getMeSomeQualityHumor())

export function averagePrice(products: Product[]) {
const prices = products.map((p) => p.price ?? 0)
return sum(prices) / prices.length
}

export const getStaticProps = async () => {
const {products} = await getProducts({orderBy: {id: "desc"}})
return {
Expand Down
8 changes: 1 addition & 7 deletions examples/store/app/products/queries/getProducts.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import {Middleware, paginate} from "blitz"
import db, {Prisma, Product} from "db"
import {sum} from "lodash"

export function averagePrice(products: Product[]) {
const prices = products.map((p) => p.price ?? 0)
return sum(prices) / prices.length
}
import db, {Prisma} from "db"

type GetProductsInput = {
where?: Prisma.ProductFindManyArgs["where"]
Expand Down
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: process.env.NEXT_TEST_JOB ? false : true,
enableBlurryPlaceholder: false,
disableOptimizedLoading: true,
gzipSize: true,
Expand Down
1 change: 1 addition & 0 deletions nextjs/packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"node-fetch": "2.6.1",
"node-html-parser": "1.4.9",
"node-libs-browser": "^2.2.1",
"null-loader": "4.0.1",
"os-browserify": "0.3.0",
"p-limit": "3.1.0",
"path-browserify": "1.0.1",
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 = {}
Loading