1

We are in the process of updating our code base to replace RequireJS with ES6 modules. There are several instances where we have components that load their own CSS and use the require.toUrl to get an absolute path. The components only know their local directory where its CSS lives, and could be in different directory structures depending on how they are deployed.

For example:

if(!document.getElementById('my-component-css')) {
    let cssRef = document.createElement('link');
    cssRef.rel = 'stylesheet';
    cssRef.type = 'text/css';
    cssRef.id = 'my-component-css';
    cssRef.href = require.toUrl('./css/my-component.min.css');
    document.head.appendChild(cssRef);
}

or we also use local imagery with CesiumJS that requires something similar:

var natEarth = new Cesium.TileMapServiceImageryProvider({
    url: require.toUrl('./assets/imagery/NaturalEarthII/'),
    fileExtension: 'jpg',
    credit: 'Imagery courtesy of NASA World Wind (Blue Marble)'
});

Looking at requireJS's code, they keep their own path structure internally and walk up the module tree to get a full absolute path for a component.

Short of passing in a path to these components (or using webpack since we cannot use it due to internal company policies), is there an equivalent in Vanilla JS to require.toUrl?

Magneton
  • 35
  • 2
  • 10
  • 1
    Yes, dynamic import, see this example https://stackoverflow.com/a/57367916/2494754 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports – NVRM Mar 01 '21 at 02:28
  • Sure, I use dynamic import for module loading in several cases, but that doesn't help with CSS paths, nor with Cesium Imagery Provider that just needs an absolute path to the Imagery Files. – Magneton Mar 01 '21 at 14:50
  • This would be way easier to generate the full path server side, this will render the page faster (no js) with less code? – NVRM Mar 01 '21 at 16:27

0 Answers0