Search code examples
javascriptphprequirejsamdnette

RequireJS with PHP and nice URL


I've been trying to solve this issue for hours now and wasn't able to find solution on my own nor on the internet, so finally I gave up and decided to post a question.

I'm trying to build my new PHP app with javascript managed as AMD, using RequireJS. It is my first time using this approach and I'm really excited about it, but there is one problem that keeps my javascript from functioning.

It is nice url done by routing. (I use Nette Framework for routes and Apache as webserver). After I set up requrejs and my dependencies, everything works fine with the homepage (localhost/), but when I go to some other page, which has URL something like localhost/news, it stops working and requirejs complains about nonexisting scripts in for example "localhost/testapp/news/js/vendor/jquery/dist/jquery.js". It should instead look in "localhost/testapp/js/vendor/jquery/dist/jquery.js", but it takes the argument (in this case presenter name) rewriten by mod_rewrite as part of the base url. I believe that the fault is somewhere on my side, since this has to be very common setup and I was not able to find simillar question.

requirejs in layout.latte (base template):

<script src="{$basePath}/js/vendor/requirejs/require.js"></script>
<script>
    var absolute_base = {$basePath};
    require([absolute_base + '/js/app.js']);
</script>

(in basePath variable in Nette framework is always the root of the app, regardless of further parameters - in this case, /testapp)

app.js

requirejs.config({
    baseUrl: 'js/modules',
    paths: {
        'jquery': '../vendor/jquery/dist/jquery',
        'ink': '../vendor/InkJS/dist/js/ink-all',
        'ajax': '../vendor/ajax'
    }
});

dir structure:

 - www
    - css
    - sass
    - graphics
    - fonts
    - js
        - modules
        - vendor
            - jquery
            - requirejs
            - ink
        - app.js
    - index.php

This is as far as I have get. I have tried lots of combinations, relative paths, dots in front of paths, data attribute for script tag etc. and haven't been able to find a solution.

Any help is greatly appreciated, cheers!


Solution

  • I finally made it work. I found out, that it could not be done in this manner, because requirejs will always use the current url as the "root", not the URL of the script itself (used in "script" tag). At least I haven't find a way how to get around this.

    Instead, I've removed the whole app.js file and moved configuration right into the main template with php variable $basePath available, which I used to define the basePath (basicly I defined an absolute path instead of a relative one).