ruffle/web/packages/core/src/public-path.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-11-17 21:01:56 +00:00
import { Config } from "./config";
2019-10-15 02:52:53 +00:00
/**
* Attempt to discover the public path of the current Ruffle source. This can
* be used to configure Webpack.
*
* A global public path can be specified for all sources using the RufflePlayer
* config:
*
* ```js
* window.RufflePlayer.config.publicPath = "/dist/";
* ```
*
* If no such config is specified, then the parent path of where this script is
* hosted is assumed, which should be the correct default in most cases.
*
* @param config The `window.RufflePlayer.config` object.
* @returns The public path for the given source.
2019-10-15 02:52:53 +00:00
*/
export function publicPath(config: Config): string {
2020-11-17 22:16:35 +00:00
let path = "";
if (config !== undefined && config.publicPath !== undefined) {
path = config.publicPath;
} else if (
document.currentScript !== undefined &&
document.currentScript !== null &&
"src" in document.currentScript &&
document.currentScript.src !== ""
) {
// Default to the directory where this script resides.
try {
2020-11-17 22:16:35 +00:00
path = new URL(".", document.currentScript.src).href;
} catch (e) {
console.warn("Unable to get currentScript URL");
}
2019-10-15 02:52:53 +00:00
}
// Webpack expects the paths to end with a slash.
2020-11-17 22:16:35 +00:00
if (path !== "" && !path.endsWith("/")) {
path += "/";
}
2020-11-17 22:16:35 +00:00
return path;
}