How to correctly get site url inside js file within magento module?
It should contain protocol (http | https) and domain name.
No path required.
Format http://example.com
If you are following best practices and using Require JS to load your Javascript this is a simple task. If you are not following best practices, now is the time to start ;)
I believe the best way is to pass the URL to the JS file via the PHTML template like so:
Template file
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"tenLooks": {
"component": "Ben_AppTest/js/ten-looks",
"dataUrl": "<?php echo $block->getViewFileUrl('Ben_AppTest::js/data.js'); ?>"
}
}
}
}
}
</script>
Javascript File
define(['uiComponent'], function(Component) {
'use strict';
return Component.extend({
initialize: function() {
console.log(this.dataUrl);
}
});
});
You should not get the base url in your JS files.
Write your js files are ui widgets and the base url should be a parameter.
Then pass that parameter from the template that uses the ui widget.