URL 解析與序列化
- path-to-regexp:
path-to-regexp
專注於路由模式的解析,並不處理查詢字串或片段。 - uri-js:
uri-js
提供全面的 URI 解析和序列化,支持各種 URI 組件。 - query-string:
query-string
提供查詢字串的解析和序列化,支持嵌套物件和陣列。 - url-template:
url-template
提供基於模板的 URL 生成,解析功能較為簡單。 - uri-template:
uri-template
專注於根據模板生成 URL,不處理查詢字串。 - template-url:
template-url
不處理解析,專注於根據模板生成 URL。
查詢字串處理
- path-to-regexp:
不處理查詢字串。
- uri-js:
提供基本的查詢字串處理,但不專注於此。
- query-string:
提供強大的查詢字串解析和序列化功能,支持嵌套和陣列。
- url-template:
不處理查詢字串。
- uri-template:
不處理查詢字串。
- template-url:
不處理查詢字串。
模板支持
- path-to-regexp:
不支持模板。
- uri-js:
不支持模板。
- query-string:
不支持模板。
- url-template:
支持基於模板生成 URL,解析模板中的佔位符。
- uri-template:
支持根據 URI 模板生成 URL,符合 RFC 6570 標準。
- template-url:
支持使用佔位符和自定義分隔符生成 URL。
輕量級與性能
- path-to-regexp:
path-to-regexp
非常輕量,性能優越,特別是在處理路由時。 - uri-js:
uri-js
相對較大,但提供全面的 URI 處理功能,性能在可接受範圍內。 - query-string:
query-string
也很輕量,對查詢字串的解析和序列化非常高效。 - url-template:
url-template
輕量級,適合需要快速模板解析和生成的應用。 - uri-template:
uri-template
輕量,專注於模板處理,性能良好。 - template-url:
template-url
輕量且性能良好,適合快速生成 URL。
代碼示例
- path-to-regexp:
路由參數解析示例
import { pathToRegexp, match } from 'path-to-regexp'; const pattern = '/users/:id'; const keys = []; const regexp = pathToRegexp(pattern, keys); const result = regexp.exec('/users/123'); console.log(result); // [ '/users/123', '123', index: 0, input: '/users/123', groups: undefined ] console.log(keys); // [ { name: 'id', prefix: ':', delimiter: '/', optional: false, repeat: false } ]
- uri-js:
URI 解析示例
import { URI } from 'uri-js'; const uri = URI.parse('https://example.com:8080/path?query=123#fragment'); console.log(uri); // { scheme: 'https', authority: 'example.com:8080', path: '/path', query: 'query=123', fragment: 'fragment' } const uriString = URI.serialize(uri); console.log(uriString); // https://example.com:8080/path?query=123#fragment
- query-string:
查詢字串解析示例
import queryString from 'query-string'; const parsed = queryString.parse('?name=John&age=30&hobbies[]=reading&hobbies[]=traveling'); console.log(parsed); // { name: 'John', age: '30', hobbies: [ 'reading', 'traveling' ] } const stringified = queryString.stringify(parsed); console.log(stringified); // name=John&age=30&hobbies%5B0%5D=reading&hobbies%5B1%5D=traveling
- url-template:
URL 模板示例
import { parseTemplate, buildUrl } from 'url-template'; const template = parseTemplate('/users/{id}/posts/{postId}'); const url = template.expand({ id: 123, postId: 456 }); console.log(url); // /users/123/posts/456
- uri-template:
URI 模板生成示例
import { UriTemplate } from 'uri-template'; const template = new UriTemplate('/users/{id}/posts/{postId}'); const url = template.expand({ id: 123, postId: 456 }); console.log(url); // /users/123/posts/456
- template-url:
URL 模板生成示例
import templateUrl from 'template-url'; const url = templateUrl('/users/{id}/posts/{postId}', { id: 123, postId: 456 }); console.log(url); // /users/123/posts/456