swc-project/swc · error · anyhow::Error

failed to get parent of {v:?}

Error message

failed to get parent of {v:?}

What it means

Thrown by the Node-style import path provider in swc_ecma_transforms_module when the base for relative-specifier conversion is a FileName::Real whose PathBuf has no parent. std::path::Path::parent() returns None only for root-like paths ('/', 'C:\'), so this means the configured base/filename resolves to a filesystem root and no relative path can be computed from it.

Source

Thrown at crates/swc_ecma_transforms_module/src/path.rs:317

        let slug = slug.as_deref().or(orig_slug);

        #[cfg(debug_assertions)]
        info!("Resolved as {target:?} with slug = {slug:?}");

        let mut target = match target {
            FileName::Real(v) => v,
            FileName::Custom(s) => return Ok(self.to_specifier(s.into(), slug)),
            _ => {
                unreachable!(
                    "Node path provider does not support using `{:?}` as a target file name",
                    target
                )
            }
        };
        let mut base = match base {
            FileName::Real(v) => Cow::Borrowed(
                v.parent()
                    .ok_or_else(|| anyhow!("failed to get parent of {v:?}"))?,
            ),
            FileName::Anon => match &self.config.base_dir {
                Some(v) => Cow::Borrowed(&**v),
                None => {
                    if cfg!(target_arch = "wasm32") {
                        panic!("Please specify `filename`")
                    } else {
                        Cow::Owned(current_dir().expect("failed to get current directory"))
                    }
                }
            },
            _ => {
                unreachable!(
                    "Node path provider does not support using `{:?}` as a base file name",
                    base
                )
            }
        };

View on GitHub (pinned to d7d7434666)

Solutions

  1. Set base_dir/filename to a real directory under a parent (e.g. the project root or the source file's directory), never '/' or a bare drive root
  2. When constructing the provider programmatically, wrap FileName::Real(base) with a parent() check and fall back to a sensible default directory before calling the transform
  3. On wasm32 targets, always pass an explicit filename/base_dir - the Anon branch panics without one

Example fix

// before
let provider = NodeImportPathProvider::new(Some("/".into()), ...);

// after
let provider = NodeImportPathProvider::new(Some("/project/src".into()), ...);
Defensive patterns

Strategy: validation

Validate before calling

// Rust: reject root-like bases before constructing the provider
fn ensure_base_has_parent(base: &Path) -> anyhow::Result<PathBuf> {
    let parent = base.parent().ok_or_else(|| {
        anyhow::anyhow!("base path {} has no parent directory", base.display())
    })?;
    if parent.as_os_str().is_empty() {
        anyhow::bail!("base path {} resolves to a filesystem root", base.display());
    }
    Ok(base.to_path_buf())
}

Try / catch

match provider.resolve_target(...) {
    Err(e) if e.to_string().contains("failed to get parent") => {
        // fall back to the source file's own directory as the base
        retry_with_base(source_file.parent().unwrap().to_path_buf())?
    }
    other => other?,
}

Prevention

When it happens

Trigger: Running module transforms (CommonJS/UMD/AMD paths handling, import rewrites) where the base FileName::Real is '/' or a drive root - e.g. base_url / filename configured as '/' or a path that canonicalizes to root.

Common situations: Passing an absolute root-ish base_dir from build tooling, an empty filename string that joins to '/', or wasm32 builds where cwd fallbacks interact badly with base_dir config (the sibling branch panics on wasm32 without a filename).

Related errors


AI-assisted analysis of swc-project/swc@d7d7434666 (2026-08-16). Data as JSON: /api/errors/09f1e7f242204778. Report an issue: GitHub.