shoelace/src/utilities/base-path.ts

43 wiersze
1.6 KiB
TypeScript
Czysty Zwykły widok Historia

2021-02-26 14:09:13 +00:00
let basePath = '';
2022-12-06 16:48:57 +00:00
/** Sets the library's base path to the specified directory. */
2021-02-26 14:09:13 +00:00
export function setBasePath(path: string) {
basePath = path;
}
2022-06-07 12:59:29 +00:00
/**
* Gets the library's base path.
*
* The base path is used to load assets such as icons and images, so it needs to be set for components to work properly.
* By default, this script will look for a script ending in shoelace.js and set the base path to the directory that
* contains that file. To override this behavior, you can add the data-shoelace attribute to any script on the page
* (it probably makes the most sense to attach it to the Shoelace script, but it could also be on a bundle). The value
* can be a local folder or it can point to a CORS-enabled endpoint such as a CDN.
*
2022-12-06 16:48:57 +00:00
* <script src="bundle.js" data-shoelace="/custom/base/path"></script>
2022-06-07 12:59:29 +00:00
*
* Alternatively, you can set the base path manually using the exported setBasePath() function.
*/
2021-02-26 14:09:13 +00:00
export function getBasePath() {
2022-06-07 12:59:29 +00:00
if (!basePath) {
const scripts = [...document.getElementsByTagName('script')] as HTMLScriptElement[];
const configScript = scripts.find(script => script.hasAttribute('data-shoelace'));
2021-02-26 14:09:13 +00:00
2022-06-07 12:59:29 +00:00
if (configScript) {
// Use the data-shoelace attribute
setBasePath(configScript.getAttribute('data-shoelace')!);
} else {
const fallbackScript = scripts.find(s => /shoelace(\.min)?\.js($|\?)/.test(s.src));
let path = '';
2021-02-26 14:09:13 +00:00
2022-06-07 12:59:29 +00:00
if (fallbackScript) {
path = fallbackScript.getAttribute('src')!;
}
2021-02-26 14:09:13 +00:00
2022-06-07 12:59:29 +00:00
setBasePath(path.split('/').slice(0, -1).join('/'));
}
2021-02-26 14:09:13 +00:00
}
2021-07-12 14:36:29 +00:00
2022-06-07 12:59:29 +00:00
return basePath.replace(/\/$/, '');
2021-02-26 14:09:13 +00:00
}