Skip to content

Commit

Permalink
Merge branch 'canary' into bugfix/second-locale-in-pathname
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] committed Nov 11, 2021
2 parents 0cd402e + c791da0 commit 73f7d15
Show file tree
Hide file tree
Showing 25 changed files with 557 additions and 117 deletions.
19 changes: 18 additions & 1 deletion contributing.md
Expand Up @@ -164,7 +164,24 @@ There are two options to develop with your local version of the codebase:
yarn install --force
```

or
#### Troubleshooting

- If you see the below error while running `yarn dev` with next:

```
Failed to load SWC binary, see more info here: https://nextjs.org/docs/messages/failed-loadin
```

Try to add the below section to your `package.json`, then run again

```json
"optionalDependencies": {
"@next/swc-linux-x64-gnu": "canary",
"@next/swc-win32-x64-msvc": "canary",
"@next/swc-darwin-x64": "canary",
"@next/swc-darwin-arm64": "canary"
},
```

### Develop inside the monorepo

Expand Down
18 changes: 9 additions & 9 deletions jest.config.js
@@ -1,16 +1,16 @@
const path = require('path')
const nextJest = require('next/jest')

module.exports = {
const createJestConfig = nextJest()

// Any custom config you want to pass to Jest
const customJestConfig = {
testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.tsx'],
setupFilesAfterEnv: ['<rootDir>/jest-setup-after-env.ts'],
verbose: true,
rootDir: 'test',
modulePaths: ['<rootDir>/lib'],
transformIgnorePatterns: ['/node_modules/', '/next[/\\\\]dist/', '/.next/'],
transform: {
'.+\\.(t|j)sx?$': [
// this matches our SWC options used in https://github.com/vercel/next.js/blob/canary/packages/next/taskfile-swc.js
path.join(__dirname, './packages/next/jest.js'),
],
},
transformIgnorePatterns: ['/next[/\\\\]dist/'],
}

// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
1 change: 1 addition & 0 deletions packages/next/build/jest/__mocks__/fileMock.js
@@ -0,0 +1 @@
module.exports = 'test-file-stub'
1 change: 1 addition & 0 deletions packages/next/build/jest/__mocks__/styleMock.js
@@ -0,0 +1 @@
module.exports = {}
134 changes: 134 additions & 0 deletions packages/next/build/jest/jest.ts
@@ -0,0 +1,134 @@
import { loadEnvConfig } from '@next/env'
import { resolve, join } from 'path'
import loadConfig from '../../server/config'
import { PHASE_TEST } from '../../shared/lib/constants'
// import loadJsConfig from '../load-jsconfig'
import * as Log from '../output/log'

async function getConfig(dir: string) {
const conf = await loadConfig(PHASE_TEST, dir)
return conf
}

/**
* Loads closest package.json in the directory hierarchy
*/
function loadClosestPackageJson(dir: string, attempts = 1): any {
if (attempts > 5) {
throw new Error("Can't resolve main package.json file")
}
var mainPath = attempts === 1 ? './' : Array(attempts).join('../')
try {
return require(join(dir, mainPath + 'package.json'))
} catch (e) {
return loadClosestPackageJson(dir, attempts + 1)
}
}

console.warn(
'"next/jest" is currently experimental. https://nextjs.org/docs/messages/experimental-jest-transformer'
)

/*
// Usage in jest.config.js
const nextJest = require('next/jest');
// Optionally provide path to Next.js app which will enable loading next.config.js and .env files
const createJestConfig = nextJest({ dir })
// Any custom config you want to pass to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
*/
module.exports = function nextJest(options: { dir?: string } = {}) {
// createJestConfig
return (customJestConfig: any) => {
// Function that is provided as the module.exports of jest.config.js
// Will be called and awaited by Jest
return async () => {
let nextConfig
let paths
let resolvedBaseUrl
let isEsmProject = false
if (options.dir) {
const resolvedDir = resolve(options.dir)
const packageConfig = loadClosestPackageJson(resolvedDir)
isEsmProject = packageConfig.type === 'module'

nextConfig = await getConfig(resolvedDir)
loadEnvConfig(resolvedDir, false, Log)
// TODO: revisit when bug in SWC is fixed that strips `.css`
// const result = await loadJsConfig(resolvedDir, nextConfig)
// paths = result?.jsConfig?.compilerOptions?.paths
// resolvedBaseUrl = result.resolvedBaseUrl
}
// Ensure provided async config is supported
const resolvedJestConfig =
typeof customJestConfig === 'function'
? await customJestConfig()
: customJestConfig

return {
...resolvedJestConfig,

moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
'^.+\\.module\\.(css|sass|scss)$':
require.resolve('./object-proxy.js'),

// Handle CSS imports (without CSS modules)
'^.+\\.(css|sass|scss)$': require.resolve('./__mocks__/styleMock.js'),

// Handle image imports
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': require.resolve(
`./__mocks__/fileMock.js`
),

// Custom config will be able to override the default mappings
...(resolvedJestConfig.moduleNameMapper || {}),
},
testPathIgnorePatterns: [
// Don't look for tests in node_modules
'/node_modules/',
// Don't look for tests in the the Next.js build output
'/.next/',
// Custom config can append to testPathIgnorePatterns but not modify it
// This is to ensure `.next` and `node_modules` are always excluded
...(resolvedJestConfig.testPathIgnorePatterns || []),
],

transform: {
// Use SWC to compile tests
'^.+\\.(js|jsx|ts|tsx)$': [
require.resolve('../swc/jest-transformer'),
{
styledComponents:
nextConfig && nextConfig.experimental.styledComponents,
paths,
resolvedBaseUrl: resolvedBaseUrl,
isEsmProject,
},
],
// Allow for appending/overriding the default transforms
...(resolvedJestConfig.transform || {}),
},

transformIgnorePatterns: [
// To match Next.js behavior node_modules is not transformed
'/node_modules/',
// CSS modules are mocked so they don't need to be transformed
'^.+\\.module\\.(css|sass|scss)$',

// Custom config can append to transformIgnorePatterns but not modify it
// This is to ensure `node_modules` and .module.css/sass/scss are always excluded
...(resolvedJestConfig.transformIgnorePatterns || []),
],
}
}
}
}
37 changes: 37 additions & 0 deletions packages/next/build/jest/object-proxy.js
@@ -0,0 +1,37 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Keyan Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

// This file is largely based on https://github.com/keyz/identity-obj-proxy
// Excludes the polyfill for below Node.js 6
export default new Proxy(
{},
{
get: function getter(target, key) {
if (key === '__esModule') {
return false
}
return key
},
}
)
84 changes: 84 additions & 0 deletions packages/next/build/load-jsconfig.ts
@@ -0,0 +1,84 @@
import path from 'path'
import { fileExists } from '../lib/file-exists'
import { NextConfigComplete } from '../server/config-shared'
import * as Log from './output/log'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import { readFileSync } from 'fs'
import isError from '../lib/is-error'
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'

let TSCONFIG_WARNED = false

function parseJsonFile(filePath: string) {
const JSON5 = require('next/dist/compiled/json5')
const contents = readFileSync(filePath, 'utf8')

// Special case an empty file
if (contents.trim() === '') {
return {}
}

try {
return JSON5.parse(contents)
} catch (err) {
if (!isError(err)) throw err
const codeFrame = codeFrameColumns(
String(contents),
{
start: {
line: (err as Error & { lineNumber?: number }).lineNumber || 0,
column: (err as Error & { columnNumber?: number }).columnNumber || 0,
},
},
{ message: err.message, highlightCode: true }
)
throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`)
}
}

export default async function loadJsConfig(
dir: string,
config: NextConfigComplete
) {
let typeScriptPath: string | undefined
try {
typeScriptPath = require.resolve('typescript', { paths: [dir] })
} catch (_) {}
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath)
const useTypeScript = Boolean(
typeScriptPath && (await fileExists(tsConfigPath))
)

let jsConfig
// jsconfig is a subset of tsconfig
if (useTypeScript) {
if (
config.typescript.tsconfigPath !== 'tsconfig.json' &&
TSCONFIG_WARNED === false
) {
TSCONFIG_WARNED = true
Log.info(`Using tsconfig file: ${config.typescript.tsconfigPath}`)
}

const ts = (await Promise.resolve(
require(typeScriptPath!)
)) as typeof import('typescript')
const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath, true)
jsConfig = { compilerOptions: tsConfig.options }
}

const jsConfigPath = path.join(dir, 'jsconfig.json')
if (!useTypeScript && (await fileExists(jsConfigPath))) {
jsConfig = parseJsonFile(jsConfigPath)
}

let resolvedBaseUrl
if (jsConfig?.compilerOptions?.baseUrl) {
resolvedBaseUrl = path.resolve(dir, jsConfig.compilerOptions.baseUrl)
}
return {
useTypeScript,
jsConfig,
resolvedBaseUrl,
}
}
Expand Up @@ -30,45 +30,30 @@ import vm from 'vm'
import { transformSync } from './index'
import { getJestSWCOptions } from './options'

console.warn(
'"next/jest" is currently experimental. https://nextjs.org/docs/messages/experimental-jest-transformer'
)

/**
* Loads closest package.json in the directory hierarchy
*/
function loadClosestPackageJson(attempts = 1) {
if (attempts > 5) {
throw new Error("Can't resolve main package.json file")
}
var mainPath = attempts === 1 ? './' : Array(attempts).join('../')
try {
return require(mainPath + 'package.json')
} catch (e) {
return loadClosestPackageJson(attempts + 1)
}
}

const packageConfig = loadClosestPackageJson()
const isEsmProject = packageConfig.type === 'module'

// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.
// see https://github.com/facebook/jest/issues/9430
const isSupportEsm = 'Module' in vm

module.exports = {
process(src, filename, jestOptions) {
if (!/\.[jt]sx?$/.test(filename)) {
return src
}
createTransformer: (inputOptions) => ({
process(src, filename, jestOptions) {
if (!/\.[jt]sx?$/.test(filename)) {
return src
}

let swcTransformOpts = getJestSWCOptions({
filename,
esm: isSupportEsm && isEsm(filename, jestOptions),
})
let swcTransformOpts = getJestSWCOptions({
filename,
styledComponents: inputOptions.styledComponents,
paths: inputOptions.paths,
baseUrl: inputOptions.resolvedBaseUrl,
esm:
isSupportEsm &&
isEsm(Boolean(inputOptions.isEsmProject), filename, jestOptions),
})

return transformSync(src, { ...swcTransformOpts, filename })
},
return transformSync(src, { ...swcTransformOpts, filename })
},
}),
}

function getJestConfig(jestConfig) {
Expand All @@ -79,7 +64,7 @@ function getJestConfig(jestConfig) {
jestConfig
}

function isEsm(filename, jestOptions) {
function isEsm(isEsmProject, filename, jestOptions) {
return (
(/\.jsx?$/.test(filename) && isEsmProject) ||
getJestConfig(jestOptions).extensionsToTreatAsEsm?.find((ext) =>
Expand Down

0 comments on commit 73f7d15

Please sign in to comment.