Unverified Commit c2473471 authored by Leah's avatar Leah Committed by GitHub

feat: support custom image loaders in turbopack (#60736)

### What?
We were missing the alias (and config field) for custom image loaders.

Closes PACK-2190
Fixes #60097
parent cb71d808
...@@ -2,6 +2,7 @@ import loadConfig from 'next/dist/server/config' ...@@ -2,6 +2,7 @@ import loadConfig from 'next/dist/server/config'
import loadCustomRoutes from 'next/dist/lib/load-custom-routes' import loadCustomRoutes from 'next/dist/lib/load-custom-routes'
import { PHASE_DEVELOPMENT_SERVER } from 'next/dist/shared/lib/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next/dist/shared/lib/constants'
import assert from 'node:assert' import assert from 'node:assert'
import * as path from 'node:path'
const loadNextConfig = async (silent) => { const loadNextConfig = async (silent) => {
const nextConfig = await loadConfig( const nextConfig = await loadConfig(
...@@ -45,6 +46,12 @@ const loadNextConfig = async (silent) => { ...@@ -45,6 +46,12 @@ const loadNextConfig = async (silent) => {
) )
} }
// loaderFile is an absolute path, we need it to be relative for turbopack.
if (nextConfig.images.loaderFile) {
nextConfig.images.loaderFile =
'./' + path.relative(process.cwd(), nextConfig.images.loaderFile)
}
return { return {
customRoutes: customRoutes, customRoutes: customRoutes,
config: nextConfig, config: nextConfig,
......
...@@ -145,7 +145,7 @@ pub async fn get_client_resolve_options_context( ...@@ -145,7 +145,7 @@ pub async fn get_client_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_client_import_map = let next_client_import_map =
get_next_client_import_map(project_path, ty, mode, next_config, execution_context); get_next_client_import_map(project_path, ty, next_config, execution_context);
let next_client_fallback_import_map = get_next_client_fallback_import_map(ty); let next_client_fallback_import_map = get_next_client_fallback_import_map(ty);
let next_client_resolved_map = get_next_client_resolved_map(project_path, project_path, mode); let next_client_resolved_map = get_next_client_resolved_map(project_path, project_path, mode);
let module_options_context = ResolveOptionsContext { let module_options_context = ResolveOptionsContext {
......
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use indexmap::IndexMap; use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_tasks::{trace::TraceRawVcs, Completion, Value, Vc}; use turbo_tasks::{trace::TraceRawVcs, Completion, Value, Vc};
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
...@@ -310,6 +310,8 @@ pub struct ImageConfig { ...@@ -310,6 +310,8 @@ pub struct ImageConfig {
pub image_sizes: Vec<u16>, pub image_sizes: Vec<u16>,
pub path: String, pub path: String,
pub loader: ImageLoader, pub loader: ImageLoader,
#[serde(deserialize_with = "empty_string_is_none")]
pub loader_file: Option<String>,
pub domains: Vec<String>, pub domains: Vec<String>,
pub disable_static_images: bool, pub disable_static_images: bool,
#[serde(rename(deserialize = "minimumCacheTTL"))] #[serde(rename(deserialize = "minimumCacheTTL"))]
...@@ -322,6 +324,14 @@ pub struct ImageConfig { ...@@ -322,6 +324,14 @@ pub struct ImageConfig {
pub unoptimized: bool, pub unoptimized: bool,
} }
fn empty_string_is_none<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let o = Option::<String>::deserialize(deserializer)?;
Ok(o.filter(|s| !s.is_empty()))
}
impl Default for ImageConfig { impl Default for ImageConfig {
fn default() -> Self { fn default() -> Self {
// https://github.com/vercel/next.js/blob/327634eb/packages/next/shared/lib/image-config.ts#L100-L114 // https://github.com/vercel/next.js/blob/327634eb/packages/next/shared/lib/image-config.ts#L100-L114
...@@ -330,6 +340,7 @@ impl Default for ImageConfig { ...@@ -330,6 +340,7 @@ impl Default for ImageConfig {
image_sizes: vec![16, 32, 48, 64, 96, 128, 256, 384], image_sizes: vec![16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image".to_string(), path: "/_next/image".to_string(),
loader: ImageLoader::Default, loader: ImageLoader::Default,
loader_file: None,
domains: vec![], domains: vec![],
disable_static_images: false, disable_static_images: false,
minimum_cache_ttl: 60, minimum_cache_ttl: 60,
......
...@@ -99,7 +99,7 @@ pub async fn get_edge_resolve_options_context( ...@@ -99,7 +99,7 @@ pub async fn get_edge_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_edge_import_map = let next_edge_import_map =
get_next_edge_import_map(project_path, ty, mode, next_config, execution_context); get_next_edge_import_map(project_path, ty, next_config, execution_context);
let ty = ty.into_value(); let ty = ty.into_value();
......
...@@ -40,7 +40,6 @@ use crate::{ ...@@ -40,7 +40,6 @@ use crate::{
pub async fn get_next_client_import_map( pub async fn get_next_client_import_map(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
ty: Value<ClientContextType>, ty: Value<ClientContextType>,
mode: NextMode,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
...@@ -51,7 +50,6 @@ pub async fn get_next_client_import_map( ...@@ -51,7 +50,6 @@ pub async fn get_next_client_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
mode,
) )
.await?; .await?;
...@@ -261,7 +259,6 @@ pub fn get_next_client_fallback_import_map(ty: Value<ClientContextType>) -> Vc<I ...@@ -261,7 +259,6 @@ pub fn get_next_client_fallback_import_map(ty: Value<ClientContextType>) -> Vc<I
pub async fn get_next_server_import_map( pub async fn get_next_server_import_map(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
ty: Value<ServerContextType>, ty: Value<ServerContextType>,
mode: NextMode,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
...@@ -272,7 +269,6 @@ pub async fn get_next_server_import_map( ...@@ -272,7 +269,6 @@ pub async fn get_next_server_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
mode,
) )
.await?; .await?;
...@@ -338,7 +334,6 @@ pub async fn get_next_server_import_map( ...@@ -338,7 +334,6 @@ pub async fn get_next_server_import_map(
pub async fn get_next_edge_import_map( pub async fn get_next_edge_import_map(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
ty: Value<ServerContextType>, ty: Value<ServerContextType>,
mode: NextMode,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> { ) -> Result<Vc<ImportMap>> {
...@@ -399,7 +394,6 @@ pub async fn get_next_edge_import_map( ...@@ -399,7 +394,6 @@ pub async fn get_next_edge_import_map(
project_path, project_path,
execution_context, execution_context,
next_config, next_config,
mode,
) )
.await?; .await?;
...@@ -521,6 +515,21 @@ async fn insert_next_server_special_aliases( ...@@ -521,6 +515,21 @@ async fn insert_next_server_special_aliases(
external_if_node(project_path, "next/dist/compiled/@opentelemetry/api"), external_if_node(project_path, "next/dist/compiled/@opentelemetry/api"),
); );
let image_config = next_config.image_config().await?;
if let Some(loader_file) = image_config.loader_file.as_deref() {
import_map.insert_exact_alias(
"next/dist/shared/lib/image-loader",
request_to_import_mapping(project_path, loader_file),
);
if runtime == NextRuntime::Edge {
import_map.insert_exact_alias(
"next/dist/esm/shared/lib/image-loader",
request_to_import_mapping(project_path, loader_file),
);
}
}
match ty { match ty {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => { ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
insert_alias_to_alternatives( insert_alias_to_alternatives(
...@@ -745,7 +754,6 @@ async fn insert_next_shared_aliases( ...@@ -745,7 +754,6 @@ async fn insert_next_shared_aliases(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
mode: NextMode,
) -> Result<()> { ) -> Result<()> {
let package_root = next_js_fs().root(); let package_root = next_js_fs().root();
...@@ -761,15 +769,6 @@ async fn insert_next_shared_aliases( ...@@ -761,15 +769,6 @@ async fn insert_next_shared_aliases(
); );
} }
if mode != NextMode::Development {
// we use the next.js hydration code, so we replace the error overlay with our
// own
import_map.insert_exact_alias(
"next/dist/compiled/@next/react-dev-overlay/dist/client",
request_to_import_mapping(package_root, "./overlay/client.ts"),
);
}
insert_package_alias( insert_package_alias(
import_map, import_map,
&format!("{VIRTUAL_PACKAGE_NAME}/"), &format!("{VIRTUAL_PACKAGE_NAME}/"),
......
...@@ -104,7 +104,7 @@ pub async fn get_server_resolve_options_context( ...@@ -104,7 +104,7 @@ pub async fn get_server_resolve_options_context(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_server_import_map = let next_server_import_map =
get_next_server_import_map(project_path, ty, mode, next_config, execution_context); get_next_server_import_map(project_path, ty, next_config, execution_context);
let foreign_code_context_condition = let foreign_code_context_condition =
foreign_code_context_condition(next_config, project_path).await?; foreign_code_context_condition(next_config, project_path).await?;
let root_dir = project_path.root().resolve().await?; let root_dir = project_path.root().resolve().await?;
......
...@@ -796,7 +796,8 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -796,7 +796,8 @@ function bindingToApi(binding: any, _wasm: boolean) {
return { return {
...options, ...options,
nextConfig: nextConfig:
options.nextConfig && (await serializeNextConfig(options.nextConfig)), options.nextConfig &&
(await serializeNextConfig(options.nextConfig, options.projectPath!)),
jsConfig: options.jsConfig && JSON.stringify(options.jsConfig), jsConfig: options.jsConfig && JSON.stringify(options.jsConfig),
env: options.env && rustifyEnv(options.env), env: options.env && rustifyEnv(options.env),
defineEnv: options.defineEnv, defineEnv: options.defineEnv,
...@@ -810,7 +811,7 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -810,7 +811,7 @@ function bindingToApi(binding: any, _wasm: boolean) {
this._nativeProject = nativeProject this._nativeProject = nativeProject
} }
async update(options: ProjectOptions) { async update(options: Partial<ProjectOptions>) {
await withErrorCause(async () => await withErrorCause(async () =>
binding.projectUpdate( binding.projectUpdate(
this._nativeProject, this._nativeProject,
...@@ -1037,7 +1038,8 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -1037,7 +1038,8 @@ function bindingToApi(binding: any, _wasm: boolean) {
} }
async function serializeNextConfig( async function serializeNextConfig(
nextConfig: NextConfigComplete nextConfig: NextConfigComplete,
projectPath: string
): Promise<string> { ): Promise<string> {
let nextConfigSerializable = nextConfig as any let nextConfigSerializable = nextConfig as any
...@@ -1073,6 +1075,12 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -1073,6 +1075,12 @@ function bindingToApi(binding: any, _wasm: boolean) {
) )
: undefined : undefined
// loaderFile is an absolute path, we need it to be relative for turbopack.
if (nextConfig.images.loaderFile) {
nextConfig.images.loaderFile =
'./' + path.relative(projectPath, nextConfig.images.loaderFile)
}
return JSON.stringify(nextConfigSerializable, null, 2) return JSON.stringify(nextConfigSerializable, null, 2)
} }
......
...@@ -13495,12 +13495,11 @@ ...@@ -13495,12 +13495,11 @@
"test/integration/next-image-new/loader-config-default-loader-with-file/test/index.test.ts": { "test/integration/next-image-new/loader-config-default-loader-with-file/test/index.test.ts": {
"passed": [ "passed": [
"Image Loader Config dev mode - component should work with loader prop", "Image Loader Config dev mode - component should work with loader prop",
"Image Loader Config dev mode - getImageProps should work with loader prop"
],
"failed": [
"Image Loader Config dev mode - component should work with loaderFile config, leaving default image optimization enabled", "Image Loader Config dev mode - component should work with loaderFile config, leaving default image optimization enabled",
"Image Loader Config dev mode - getImageProps should work with loader prop",
"Image Loader Config dev mode - getImageProps should work with loaderFile config, leaving default image optimization enabled" "Image Loader Config dev mode - getImageProps should work with loaderFile config, leaving default image optimization enabled"
], ],
"failed": [],
"pending": [ "pending": [
"Image Loader Config production mode - component should work with loader prop", "Image Loader Config production mode - component should work with loader prop",
"Image Loader Config production mode - component should work with loaderFile config, leaving default image optimization enabled", "Image Loader Config production mode - component should work with loaderFile config, leaving default image optimization enabled",
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