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

Transpile geist by default #67402

Merged
merged 10 commits into from
Jul 4, 2024
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
19 changes: 13 additions & 6 deletions packages/next-swc/crates/next-core/src/next_server/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,11 @@ pub async fn get_server_resolve_options_context(
let invalid_styled_jsx_client_only_resolve_plugin =
get_invalid_styled_jsx_resolve_plugin(project_path);

let mut transpile_packages = next_config.transpile_packages().await?.clone_value();
transpile_packages.extend(
(*next_config.optimize_package_imports().await?)
.iter()
.cloned(),
);
let default_transpiled_packages: Vec<RcStr> = load_next_js_templateon(
huozhi marked this conversation as resolved.
Show resolved Hide resolved
project_path,
"dist/lib/default-transpiled-packages.json".into(),
)
.await?;

// Always load these predefined packages as external.
let mut external_packages: Vec<RcStr> = load_next_js_templateon(
Expand All @@ -154,6 +153,14 @@ pub async fn get_server_resolve_options_context(
)
.await?;

let mut transpile_packages = next_config.transpile_packages().await?.clone_value();
transpile_packages.extend(
(*next_config.optimize_package_imports().await?)
.iter()
.cloned(),
);
transpile_packages.extend(default_transpiled_packages.iter().cloned());

let server_external_packages = &*next_config.server_external_packages().await?;

let conflicting_packages = transpile_packages
Expand Down
47 changes: 29 additions & 18 deletions packages/next-swc/crates/next-core/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,29 @@ pub fn get_asset_path_from_pathname(pathname: &str, ext: &str) -> String {
format!("{}{}", get_asset_prefix_from_pathname(pathname), ext)
}

#[turbo_tasks::function]
pub async fn get_transpiled_package(
huozhi marked this conversation as resolved.
Show resolved Hide resolved
next_config: Vc<NextConfig>,
project_path: Vc<FileSystemPath>,
) -> Result<Vc<Vec<RcStr>>> {
let mut transpile_packages: Vec<RcStr> = next_config.transpile_packages().await?.clone_value();

let default_transpiled_packages: Vec<RcStr> = load_next_js_templateon(
project_path,
"dist/lib/default-transpiled-packages.json".into(),
)
.await?;

transpile_packages.extend(default_transpiled_packages.iter().cloned());

Ok(Vc::cell(transpile_packages))
}

pub async fn foreign_code_context_condition(
next_config: Vc<NextConfig>,
project_path: Vc<FileSystemPath>,
) -> Result<ContextCondition> {
let transpile_packages = next_config.transpile_packages().await?;
let transpiled_packages = get_transpiled_package(next_config, project_path).await?;

// The next template files are allowed to import the user's code via import
// mapping, and imports must use the project-level [ResolveOptions] instead
Expand All @@ -103,23 +121,16 @@ pub async fn foreign_code_context_condition(
get_next_package(project_path).join(NEXT_TEMPLATE_PATH.into()),
));

let result = if transpile_packages.is_empty() {
ContextCondition::all(vec![
ContextCondition::InDirectory("node_modules".to_string()),
not_next_template_dir,
])
} else {
ContextCondition::all(vec![
ContextCondition::InDirectory("node_modules".to_string()),
not_next_template_dir,
ContextCondition::not(ContextCondition::any(
transpile_packages
.iter()
.map(|package| ContextCondition::InDirectory(format!("node_modules/{package}")))
.collect(),
)),
])
};
let result = ContextCondition::all(vec![
ContextCondition::InDirectory("node_modules".to_string()),
not_next_template_dir,
ContextCondition::not(ContextCondition::any(
transpiled_packages
.iter()
.map(|package| ContextCondition::InDirectory(format!("node_modules/{package}")))
.collect(),
)),
]);
Ok(result)
}

Expand Down
11 changes: 8 additions & 3 deletions packages/next/src/build/handle-externals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,13 @@ export function makeExternalHandler({
config,
optOutBundlingPackages,
optOutBundlingPackageRegex,
transpiledPackages,
dir,
}: {
config: NextConfigComplete
optOutBundlingPackages: string[]
optOutBundlingPackageRegex: RegExp
transpiledPackages: string[]
dir: string
}) {
let resolvedExternalPackageDirs: Map<string, string>
Expand Down Expand Up @@ -322,10 +324,10 @@ export function makeExternalHandler({

// If a package should be transpiled by Next.js, we skip making it external.
// It doesn't matter what the extension is, as we'll transpile it anyway.
if (config.transpilePackages && !resolvedExternalPackageDirs) {
if (transpiledPackages && !resolvedExternalPackageDirs) {
resolvedExternalPackageDirs = new Map()
// We need to resolve all the external package dirs initially.
for (const pkg of config.transpilePackages) {
for (const pkg of transpiledPackages) {
const pkgRes = await resolveExternal(
dir,
config.experimental.esmExternals,
Expand All @@ -350,6 +352,7 @@ export function makeExternalHandler({
externalType,
isOptOutBundling,
request,
transpiledPackages,
})
if (resolvedBundlingOptOutRes) {
return resolvedBundlingOptOutRes
Expand All @@ -368,6 +371,7 @@ function resolveBundlingOptOutPackages({
externalType,
isOptOutBundling,
request,
transpiledPackages,
}: {
resolvedRes: string
config: NextConfigComplete
Expand All @@ -376,6 +380,7 @@ function resolveBundlingOptOutPackages({
externalType: string
isOptOutBundling: boolean
request: string
transpiledPackages: string[]
}) {
if (nodeModulesRegex.test(resolvedRes)) {
const shouldBundlePages =
Expand All @@ -385,7 +390,7 @@ function resolveBundlingOptOutPackages({
shouldBundlePages ||
isResourceInPackages(
resolvedRes,
config.transpilePackages,
transpiledPackages,
resolvedExternalPackageDirs
)

Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/build/jest/jest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { loadBindings, lockfilePatchPromise } from '../swc'
import type { JestTransformerConfig } from '../swc/jest-transformer'
import type { Config } from '@jest/types'

const DEFAULT_TRANSPILED_PACKAGES: string[] = require('../../lib/default-transpiled-packages.json')

async function getConfig(dir: string) {
const conf = await loadConfig(PHASE_TEST, dir)
return conf
Expand Down Expand Up @@ -100,7 +102,9 @@ export default function nextJest(options: { dir?: string } = {}) {
await lockfilePatchPromise.cur
}

const transpiled = (nextConfig?.transpilePackages ?? []).join('|')
const transpiled = (nextConfig?.transpilePackages ?? [])
.concat(DEFAULT_TRANSPILED_PACKAGES)
.join('|')

const jestTransformerConfig: JestTransformerConfig = {
modularizeImports: nextConfig?.modularizeImports,
Expand Down
8 changes: 7 additions & 1 deletion packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ type ClientEntries = {
const EXTERNAL_PACKAGES =
require('../lib/server-external-packages.json') as string[]

const DEFAULT_TRANSPILED_PACKAGES =
require('../lib/default-transpiled-packages.json') as string[]

export const NEXT_PROJECT_ROOT = path.join(__dirname, '..', '..')
export const NEXT_PROJECT_ROOT_DIST = path.join(NEXT_PROJECT_ROOT, 'dist')
const NEXT_PROJECT_ROOT_DIST_CLIENT = path.join(
Expand Down Expand Up @@ -395,7 +398,9 @@ export default async function getBaseWebpackConfig(

// since `pages` doesn't always bundle by default we need to
// auto-include optimizePackageImports in transpilePackages
const finalTranspilePackages: string[] = config.transpilePackages || []
const finalTranspilePackages: string[] = (
config.transpilePackages || []
).concat(DEFAULT_TRANSPILED_PACKAGES)

for (const pkg of config.experimental.optimizePackageImports || []) {
if (!finalTranspilePackages.includes(pkg)) {
Expand Down Expand Up @@ -855,6 +860,7 @@ export default async function getBaseWebpackConfig(
config,
optOutBundlingPackages,
optOutBundlingPackageRegex,
transpiledPackages: finalTranspilePackages,
dir,
})

Expand Down
1 change: 1 addition & 0 deletions packages/next/src/lib/default-transpiled-packages.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["geist"]
19 changes: 19 additions & 0 deletions test/e2e/geist-font/geist-font.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { nextTestSetup } from 'e2e-utils'
import { assertNoRedbox } from 'next-test-utils'

describe('geist-font', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
geist: 'latest',
},
})

it('should work with geist font in pages router', async () => {
const browser = await next.browser('/foo')

await assertNoRedbox(browser)
const text = await browser.elementByCss('p').text()
expect(text).toBe('Foo page')
})
})
9 changes: 9 additions & 0 deletions test/e2e/geist-font/pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { GeistSans } from 'geist/font/sans'

export default function MyApp({ Component, pageProps }) {
return (
<main className={GeistSans.className}>
<Component {...pageProps} />
</main>
)
}
3 changes: 3 additions & 0 deletions test/e2e/geist-font/pages/foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p>Foo page</p>
}
Loading