Unverified Commit 7bdb61c2 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix bugs with baseUrl and mdxRs (#58968)

## What?

Was investigating an issue with Turbopack and MDX, in the process found
a few bugs:

- When you have a `tsconfig.json` or `jsconfig.json` the `baseUrl: '.'`
is used by default which causes the top-level directories to be
available as e.g. `design-system` (without a prefix).
- This is not how TypeScript's default setting for `baseUrl` works.
While it should resolve `paths` relative to `.` when none is specified
it does not do additional resolving for the top level directories/files.
- When `"baseUrl": "."` is added to `tsconfig.js` explicitly it handles
the top level directories.
- `modularizeImports` and other SWC transforms weren't applied to `.mdx`
files when `experimental.mdxRs` is enabled, which caused compilation to
fail.
- `modularIzeImports` and other SWC transforms are not applied to `.mdx`
files when using Turbopack.
	- @kwonoj is investigating this, will be handled in a follow-up PR.

## How?

- Added a test suite for `modularizeImports` with MDX tests
- Removed the condition that disables swcLoader in webpack when using
mdxRs
- Changed the check for `tsconfig.json` / `jsconfig.json` baseUrl to
include if it was implicitly or explicitly set, disabled the module
resolving when it is implicitly set


<!-- 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 #

-->

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 0d6d53cc
...@@ -28,12 +28,7 @@ module.exports = ...@@ -28,12 +28,7 @@ module.exports =
] ]
config.module.rules.push({ config.module.rules.push({
test: extension, test: extension,
use: [ use: [options.defaultLoaders.babel, loader],
nextConfig?.experimental?.mdxRs
? undefined
: options.defaultLoaders.babel,
loader,
].filter(Boolean),
}) })
if (typeof nextConfig.webpack === 'function') { if (typeof nextConfig.webpack === 'function') {
......
...@@ -37,10 +37,20 @@ function parseJsonFile(filePath: string) { ...@@ -37,10 +37,20 @@ function parseJsonFile(filePath: string) {
} }
} }
export type ResolvedBaseUrl =
| { baseUrl: string; isImplicit: boolean }
| undefined
export type JsConfig = { compilerOptions: Record<string, any> } | undefined
export default async function loadJsConfig( export default async function loadJsConfig(
dir: string, dir: string,
config: NextConfigComplete config: NextConfigComplete
) { ): Promise<{
useTypeScript: boolean
jsConfig: JsConfig
resolvedBaseUrl: ResolvedBaseUrl
}> {
let typeScriptPath: string | undefined let typeScriptPath: string | undefined
try { try {
const deps = await hasNecessaryDependencies(dir, [ const deps = await hasNecessaryDependencies(dir, [
...@@ -81,12 +91,18 @@ export default async function loadJsConfig( ...@@ -81,12 +91,18 @@ export default async function loadJsConfig(
implicitBaseurl = path.dirname(jsConfigPath) implicitBaseurl = path.dirname(jsConfigPath)
} }
let resolvedBaseUrl let resolvedBaseUrl: ResolvedBaseUrl
if (jsConfig) { if (jsConfig?.compilerOptions?.baseUrl) {
if (jsConfig.compilerOptions?.baseUrl) { resolvedBaseUrl = {
resolvedBaseUrl = path.resolve(dir, jsConfig.compilerOptions.baseUrl) baseUrl: path.resolve(dir, jsConfig.compilerOptions.baseUrl),
} else { isImplicit: false,
resolvedBaseUrl = implicitBaseurl }
} else {
if (implicitBaseurl) {
resolvedBaseUrl = {
baseUrl: implicitBaseurl,
isImplicit: true,
}
} }
} }
......
...@@ -36,11 +36,12 @@ import type { ...@@ -36,11 +36,12 @@ import type {
} from '@jest/transform' } from '@jest/transform'
import type { Config } from '@jest/types' import type { Config } from '@jest/types'
import type { NextConfig, ExperimentalConfig } from '../../server/config-shared' import type { NextConfig, ExperimentalConfig } from '../../server/config-shared'
import type { ResolvedBaseUrl } from '../load-jsconfig'
type TransformerConfig = Config.TransformerConfig[1] type TransformerConfig = Config.TransformerConfig[1]
export interface JestTransformerConfig extends TransformerConfig { export interface JestTransformerConfig extends TransformerConfig {
jsConfig: any jsConfig: any
resolvedBaseUrl?: string resolvedBaseUrl?: ResolvedBaseUrl
pagesDir?: string pagesDir?: string
serverComponents?: boolean serverComponents?: boolean
isEsmProject: boolean isEsmProject: boolean
......
...@@ -4,6 +4,7 @@ import type { ...@@ -4,6 +4,7 @@ import type {
EmotionConfig, EmotionConfig,
StyledComponentsConfig, StyledComponentsConfig,
} from '../../server/config-shared' } from '../../server/config-shared'
import type { ResolvedBaseUrl } from '../load-jsconfig'
const nextDistPath = const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/ /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
...@@ -52,7 +53,7 @@ function getBaseSWCOptions({ ...@@ -52,7 +53,7 @@ function getBaseSWCOptions({
modularizeImports?: NextConfig['modularizeImports'] modularizeImports?: NextConfig['modularizeImports']
compilerOptions: NextConfig['compiler'] compilerOptions: NextConfig['compiler']
swcPlugins: ExperimentalConfig['swcPlugins'] swcPlugins: ExperimentalConfig['swcPlugins']
resolvedBaseUrl?: string resolvedBaseUrl?: ResolvedBaseUrl
jsConfig: any jsConfig: any
swcCacheDir?: string swcCacheDir?: string
serverComponents?: boolean serverComponents?: boolean
...@@ -77,7 +78,7 @@ function getBaseSWCOptions({ ...@@ -77,7 +78,7 @@ function getBaseSWCOptions({
jsc: { jsc: {
...(resolvedBaseUrl && paths ...(resolvedBaseUrl && paths
? { ? {
baseUrl: resolvedBaseUrl, baseUrl: resolvedBaseUrl.baseUrl,
paths, paths,
} }
: {}), : {}),
...@@ -257,7 +258,7 @@ export function getJestSWCOptions({ ...@@ -257,7 +258,7 @@ export function getJestSWCOptions({
swcPlugins: ExperimentalConfig['swcPlugins'] swcPlugins: ExperimentalConfig['swcPlugins']
compilerOptions: NextConfig['compiler'] compilerOptions: NextConfig['compiler']
jsConfig: any jsConfig: any
resolvedBaseUrl?: string resolvedBaseUrl?: ResolvedBaseUrl
pagesDir?: string pagesDir?: string
serverComponents?: boolean serverComponents?: boolean
}) { }) {
...@@ -298,6 +299,8 @@ export function getJestSWCOptions({ ...@@ -298,6 +299,8 @@ export function getJestSWCOptions({
} }
export function getLoaderSWCOptions({ export function getLoaderSWCOptions({
// This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl,
filename, filename,
development, development,
isServer, isServer,
...@@ -316,9 +319,7 @@ export function getLoaderSWCOptions({ ...@@ -316,9 +319,7 @@ export function getLoaderSWCOptions({
relativeFilePathFromRoot, relativeFilePathFromRoot,
serverComponents, serverComponents,
isReactServerLayer, isReactServerLayer,
}: // This is not passed yet as "paths" resolving is handled by webpack currently. }: {
// resolvedBaseUrl,
{
filename: string filename: string
development: boolean development: boolean
isServer: boolean isServer: boolean
......
...@@ -51,7 +51,10 @@ import type { ...@@ -51,7 +51,10 @@ import type {
} from './webpack/plugins/telemetry-plugin' } from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace' import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info' import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import loadJsConfig from './load-jsconfig' import loadJsConfig, {
type JsConfig,
type ResolvedBaseUrl,
} from './load-jsconfig'
import { loadBindings } from './swc' import { loadBindings } from './swc'
import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plugin' import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plugin'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin' import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
...@@ -231,7 +234,11 @@ export async function loadProjectInfo({ ...@@ -231,7 +234,11 @@ export async function loadProjectInfo({
dir: string dir: string
config: NextConfigComplete config: NextConfigComplete
dev: boolean dev: boolean
}) { }): Promise<{
jsConfig: JsConfig
resolvedBaseUrl: ResolvedBaseUrl
supportedBrowsers: string[] | undefined
}> {
const { jsConfig, resolvedBaseUrl } = await loadJsConfig(dir, config) const { jsConfig, resolvedBaseUrl } = await loadJsConfig(dir, config)
const supportedBrowsers = await getSupportedBrowsers(dir, dev) const supportedBrowsers = await getSupportedBrowsers(dir, dev)
return { return {
...@@ -310,7 +317,7 @@ export default async function getBaseWebpackConfig( ...@@ -310,7 +317,7 @@ export default async function getBaseWebpackConfig(
middlewareMatchers?: MiddlewareMatcher[] middlewareMatchers?: MiddlewareMatcher[]
noMangling?: boolean noMangling?: boolean
jsConfig: any jsConfig: any
resolvedBaseUrl: string | undefined resolvedBaseUrl: ResolvedBaseUrl
supportedBrowsers: string[] | undefined supportedBrowsers: string[] | undefined
clientRouterFilters?: { clientRouterFilters?: {
staticFilter: ReturnType< staticFilter: ReturnType<
...@@ -1802,16 +1809,17 @@ export default async function getBaseWebpackConfig( ...@@ -1802,16 +1809,17 @@ export default async function getBaseWebpackConfig(
} }
// Support tsconfig and jsconfig baseUrl // Support tsconfig and jsconfig baseUrl
if (resolvedBaseUrl) { // Only add the baseUrl if it's explicitly set in tsconfig/jsconfig
webpackConfig.resolve?.modules?.push(resolvedBaseUrl) if (resolvedBaseUrl && !resolvedBaseUrl.isImplicit) {
webpackConfig.resolve?.modules?.push(resolvedBaseUrl.baseUrl)
} }
// allows add JsConfigPathsPlugin to allow hot-reloading // always add JsConfigPathsPlugin to allow hot-reloading
// if the config is added/removed // if the config is added/removed
webpackConfig.resolve?.plugins?.unshift( webpackConfig.resolve?.plugins?.unshift(
new JsConfigPathsPlugin( new JsConfigPathsPlugin(
jsConfig?.compilerOptions?.paths || {}, jsConfig?.compilerOptions?.paths || {},
resolvedBaseUrl || dir resolvedBaseUrl
) )
) )
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
import path from 'path' import path from 'path'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { debug } from 'next/dist/compiled/debug' import { debug } from 'next/dist/compiled/debug'
import type { ResolvedBaseUrl } from '../../load-jsconfig'
const log = debug('next:jsconfig-paths-plugin') const log = debug('next:jsconfig-paths-plugin')
...@@ -168,10 +169,10 @@ type Paths = { [match: string]: string[] } ...@@ -168,10 +169,10 @@ type Paths = { [match: string]: string[] }
*/ */
export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance { export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance {
paths: Paths paths: Paths
resolvedBaseUrl: string resolvedBaseUrl: ResolvedBaseUrl
jsConfigPlugin: true jsConfigPlugin: true
constructor(paths: Paths, resolvedBaseUrl: string) { constructor(paths: Paths, resolvedBaseUrl: ResolvedBaseUrl) {
this.paths = paths this.paths = paths
this.resolvedBaseUrl = resolvedBaseUrl this.resolvedBaseUrl = resolvedBaseUrl
this.jsConfigPlugin = true this.jsConfigPlugin = true
...@@ -189,6 +190,10 @@ export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance { ...@@ -189,6 +190,10 @@ export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance {
resolveContext: any, resolveContext: any,
callback: (err?: any, result?: any) => void callback: (err?: any, result?: any) => void
) => { ) => {
const resolvedBaseUrl = this.resolvedBaseUrl
if (resolvedBaseUrl === undefined) {
return callback()
}
const paths = this.paths const paths = this.paths
const pathsKeys = Object.keys(paths) const pathsKeys = Object.keys(paths)
...@@ -248,7 +253,7 @@ export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance { ...@@ -248,7 +253,7 @@ export class JsConfigPathsPlugin implements webpack.ResolvePluginInstance {
// try next path candidate // try next path candidate
return pathCallback() return pathCallback()
} }
const candidate = path.join(this.resolvedBaseUrl, curPath) const candidate = path.join(resolvedBaseUrl.baseUrl, curPath)
const obj = Object.assign({}, request, { const obj = Object.assign({}, request, {
request: candidate, request: candidate,
}) })
......
...@@ -2083,15 +2083,21 @@ async function startWatcher(opts: SetupOpts) { ...@@ -2083,15 +2083,21 @@ async function startWatcher(opts: SetupOpts) {
(item) => item === currentResolvedBaseUrl (item) => item === currentResolvedBaseUrl
) )
if ( if (resolvedBaseUrl) {
resolvedBaseUrl && if (
resolvedBaseUrl !== currentResolvedBaseUrl resolvedBaseUrl.baseUrl !== currentResolvedBaseUrl.baseUrl
) { ) {
// remove old baseUrl and add new one // remove old baseUrl and add new one
if (resolvedUrlIndex && resolvedUrlIndex > -1) { if (resolvedUrlIndex && resolvedUrlIndex > -1) {
config.resolve?.modules?.splice(resolvedUrlIndex, 1) config.resolve?.modules?.splice(resolvedUrlIndex, 1)
}
// If the resolvedBaseUrl is implicit we only remove the previous value.
// Only add the baseUrl if it's explicitly set in tsconfig/jsconfig
if (!resolvedBaseUrl.isImplicit) {
config.resolve?.modules?.push(resolvedBaseUrl.baseUrl)
}
} }
config.resolve?.modules?.push(resolvedBaseUrl)
} }
if (jsConfig?.compilerOptions?.paths && resolvedBaseUrl) { if (jsConfig?.compilerOptions?.paths && resolvedBaseUrl) {
......
!tsconfig.json
\ No newline at end of file
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Cart, Search } from 'design-system/icons'
export default function Page() {
return (
<>
<h1>ModularizeImports</h1>
<Cart />
<Search />
</>
)
}
export function Cart() {
return <p id="cart-icon">Cart Icon</p>
}
export function Search() {
return <p id="search-icon">Search Icon</p>
}
export function useMDXComponents(components) {
return {
...components,
}
}
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'modularizeImports',
{
files: __dirname,
dependencies: {
'@next/mdx': 'canary',
'@mdx-js/loader': '^2.2.1',
'@mdx-js/react': '^2.2.1',
},
},
({ next }) => {
it('should work', async () => {
const $ = await next.render$('/')
expect($('#cart-icon').text()).toBe('Cart Icon')
expect($('#search-icon').text()).toBe('Search Icon')
})
it('should work with MDX', async () => {
const $ = await next.render$('/mdx')
expect($('#cart-icon').text()).toBe('Cart Icon')
expect($('#search-icon').text()).toBe('Search Icon')
})
}
)
const withMDX = require('@next/mdx')()
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
modularizeImports: {
'design-system/icons': {
transform: 'design-system/icons/{{ kebabCase member }}',
skipDefaultConversion: true,
},
},
experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig)
import { Cart, Search } from 'design-system/icons'
# ModularizeImports
<Cart />
<Search />
{
"compilerOptions": {
"baseUrl": ".",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
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