Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve behavior of toUrl #1779

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Improve behavior of toUrl #1779

wants to merge 3 commits into from

Conversation

jslegers
Copy link

The current implementation seems to suggest require.toUrl should only be used to get the path of an AMD module, even though the documentation also mentions a different use :

define(["require"], function(require) {
    var cssUrl = require.toUrl("./style.css");
});

Nevertheless, this method can't be used for all kinds of paths, like relative path that don't have an extension or paths that have components after the extension (which is not uncommon for a url).

This is because require.toUrl determines the position of the extension by taking the last dot of a path and considering everything starting from that dot as an extension.

This is very annoying, especially because this makes the behavior of require.toUrl different for RequireJS and the Dojo loader and results in invalid paths in RequireJS for even paths as simple and common as ../resources/.

This could easily be fixed by determining the position of the extension with a regex, like this :

/**
 * This method finds the index of the '.' of a file extension un a valid url.
 * Regex is based on https://stackoverflow.com/questions/6997262/how-to-pull-url-file-extension-out-of-url-string-using-javascript
 */
function findExtension( url ) {
    var matchext = url.match(/\.([^\./\?\#]+)($|\?|\#)/);
    return matchext ? matchext.index : -1;
}

My pull requests contains three changes to the source code :

  • I replaced lastIndexOf with this new findExtension function for determining the position of the extension
  • I renamed the moduleNamePlusExt argument of toUrl to path, to reflect that can be used in different context
  • I updated the comment to toUrl

Allow paths without an extension or with components beyond the extension to be interpreteted correctly
@jsf-clabot
Copy link

jsf-clabot commented Apr 26, 2019

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants