如何在VS Code中用Live Server扩展本地测试基础JS路由的子路由?
我有一个AWS CloudFront函数,能把URL重定向到S3托管的多个HTML页面,代码如下:
function handler(event) { var request = event.request; var uri = request.uri; if (uri.split('/')[1] == '') { request.uri = '/index.html'; } else if (uri.split('/')[1] == 'contact'){ request.uri = '/contact.html'; } else if (uri.split('/')[1] == 'blog'){ request.uri = '/blog.html'; } else if (!uri.includes('.')) { request.uri = '/index.html'; } return request; }
这个函数运行正常,但我想在VS Code里用Live Server扩展本地测试站点,把根目录下的3个HTML文件对应到子路由:
http://127.0.0.1:5500/index.htmlhttp://127.0.0.1:5500/blog/index.htmlhttp://127.0.0.1:5500/contact/index.html
期望的子路由规则:
www.example.com
www.example.com/index.html
路由到:/index.htmlwww.example.com/foo
www.example.com/foo/123
www.example.com/foo/abc
www.example.com/foo/def/123
路由到:/foo/index.htmlwww.example.com/bar
www.example.com/bar/123
www.example.com/bar/abc
www.example.com/bar/def/123
路由到:/bar/index.html
同时希望能通过类似以下代码读取路径数组,根据路径名更改页面内容:比如blog/hello展示详情页,/blog展示列表页。
var pathArray = window.location.pathname.split('/');
实现步骤
1. 配置Live Server路由重写
在项目根目录创建.vscode/settings.json文件,添加Live Server的自定义挂载规则,实现路由映射:
{ "liveServer.settings.mount": [ ["/", "./"], ["/blog/*", "/blog/index.html"], ["/contact/*", "/contact/index.html"], ["/*", "/index.html"] ] }
规则说明:
- 根路径
/直接映射到项目根目录的index.html /blog/开头的所有路径,统一指向/blog/index.html/contact/开头的所有路径,统一指向/contact/index.html- 其他无后缀的路径(如
/foo、/foo/123),都指向根目录的index.html
2. 确认本地文件结构
确保你的项目文件结构和要求一致:
你的项目根目录/ ├── index.html ├── blog/ │ └── index.html └── contact/ └── index.html
3. 前端动态渲染页面内容
在对应页面中加入JavaScript逻辑,通过路径数组判断页面类型:
以blog/index.html为例:
var pathArray = window.location.pathname.split('/'); // 路径数组示例: // 访问 /blog → ["", "blog"] // 访问 /blog/hello → ["", "blog", "hello"] // 访问 /blog/123/abc → ["", "blog", "123", "abc"] if (pathArray.length === 2) { // 路径只有/blog,渲染博客列表页 document.body.innerHTML = ` <h1>博客列表</h1> <ul> <li><a href="/blog/hello">Hello World 博客</a></li> <li><a href="/blog/123">编号123的博客</a></li> </ul> `; } else if (pathArray.length >= 3) { // 路径包含子项,渲染博客详情页 var postSlug = pathArray[2]; document.body.innerHTML = ` <h1>博客详情:${postSlug}</h1> <p>这是文章「${postSlug}」的具体内容</p> <p><a href="/blog">回到博客列表</a></p> `; }
contact/index.html可以套用类似逻辑,根据路径动态展示不同内容。
4. 测试验证
启动Live Server后,测试以下路径是否符合预期:
http://127.0.0.1:5500→ 打开根目录index.htmlhttp://127.0.0.1:5500/blog→ 打开博客列表页http://127.0.0.1:5500/blog/hello→ 打开hello博客的详情页http://127.0.0.1:5500/contact/123→ 打开联系页的动态内容http://127.0.0.1:5500/foo→ 打开根目录index.html
内容的提问来源于stack exchange,提问作者Johnny John Boy

