Skip to content

Commit

Permalink
feat: support custom image loaders in turbopack
Browse files Browse the repository at this point in the history
  • Loading branch information
ForsakenHarmony committed Jan 17, 2024
1 parent a211566 commit b36836c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
13 changes: 12 additions & 1 deletion packages/next-swc/crates/next-core/src/next_config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use turbo_tasks::{trace::TraceRawVcs, Completion, Value, Vc};
use turbo_tasks_fs::json::parse_json_with_source_context;
Expand Down Expand Up @@ -310,6 +310,8 @@ pub struct ImageConfig {
pub image_sizes: Vec<u16>,
pub path: String,
pub loader: ImageLoader,
#[serde(deserialize_with = "empty_string_is_none")]
pub loader_file: Option<String>,
pub domains: Vec<String>,
pub disable_static_images: bool,
#[serde(rename(deserialize = "minimumCacheTTL"))]
Expand All @@ -322,6 +324,14 @@ pub struct ImageConfig {
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 {
fn default() -> Self {
// https://github.com/vercel/next.js/blob/327634eb/packages/next/shared/lib/image-config.ts#L100-L114
Expand All @@ -330,6 +340,7 @@ impl Default for ImageConfig {
image_sizes: vec![16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image".to_string(),
loader: ImageLoader::Default,
loader_file: None,
domains: vec![],
disable_static_images: false,
minimum_cache_ttl: 60,
Expand Down
15 changes: 15 additions & 0 deletions packages/next-swc/crates/next-core/src/next_import_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,21 @@ async fn insert_next_server_special_aliases(
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 {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
insert_alias_to_alternatives(
Expand Down

0 comments on commit b36836c

Please sign in to comment.