← 中文资源

简体中文版本

URL 用 base 解析相对引用

new URL 以 base 解析相对引用:普通段替换 base 末段,.. 向上爬、./ 原地,开头斜杠则从根重开;缺 base 时相对引用直接抛 TypeError。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

URL {
  href: 'file:///srv/app/public/logs/app.txt',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/logs/app.txt',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///srv/app/public/assets/logo.svg',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/assets/logo.svg',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///srv/app/public/index.html',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/srv/app/public/index.html',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
URL {
  href: 'file:///health',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/health',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
no base: true

实现说明

base 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 no base:——输出的每一行都能指回产生它的那次调用。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件的状态由几个模块级绑定持有:base。

核心语句

const base = 'file:///srv/app/public/';
new URL('logs/app.txt');

代码示例

// A base URL makes relative references resolvable
const base = 'file:///srv/app/public/';

// Plain segments replace the last path segment of the base
console.log(new URL('logs/app.txt', base));

// '..' climbs and '.' stays — both normalized
console.log(new URL('logs/../assets/logo.svg', base));
console.log(new URL('./index.html', base));

// A leading slash replaces the whole path from the root
console.log(new URL('/health', base));

// Without a base, a relative reference throws
try {
  new URL('logs/app.txt');
} catch (err) {
  console.log('no base:', err instanceof TypeError);
}