js实现 basepath
JavaScript 实现 Base Path
在 JavaScript 中实现 basePath 通常用于处理相对路径或动态设置项目的基础路径。以下是几种常见方法:
使用 window.location 获取基础路径
通过解析当前页面的 URL 获取基础路径:
const basePath = window.location.origin + window.location.pathname.split('/').slice(0, -1).join('/');
console.log(basePath); // 输出:http://example.com/your-base-path
动态设置 Base Path
在单页应用(SPA)中,可以通过环境变量或全局配置设置:
// 通过环境变量配置
const BASE_PATH = process.env.BASE_PATH || '/';
// 使用示例
const apiUrl = `${BASE_PATH}api/data`;
使用 document.baseURI
获取文档的基础 URI,适用于需要动态调整路径的场景:
const basePath = new URL('./', document.baseURI).href;
console.log(basePath); // 输出当前页面的基础路径
结合 import.meta.url(ES 模块)
在 ES 模块中,可以通过 import.meta.url 获取当前模块的基础路径:
const basePath = new URL('.', import.meta.url).pathname;
console.log(basePath); // 输出模块所在目录的路径
处理相对路径
将相对路径转换为绝对路径:
function resolvePath(relativePath, basePath = window.location.origin) {
return new URL(relativePath, basePath).href;
}
const absolutePath = resolvePath('assets/image.png', 'http://example.com/base');
console.log(absolutePath); // 输出:http://example.com/base/assets/image.png
注意事项
- 在浏览器环境中,
window.location是最常用的方法。 - 对于 Node.js 环境,需使用
path模块或__dirname处理路径。 - 动态配置时,确保路径以
/开头或结尾,避免拼接错误。







