How to Use Assetic for requireJs

2019-05-04 00:34发布

问题:

I am trying to use require.js in synfony2 project.

Here the code in the main twig file:

<script 
        data-main="{{ asset('bundles/web/js/main.js') }}" 
        src="{{ asset('vendor/js/require.js') }}">
</script>

The file vendor/js/require.js is correctly loaded but for the file bundles/web/js/main.js I get the message:

Uncaught Error: Load timeout for modules: mainApp.js?201205021855 http://requirejs.org/docs/errors.html#timeout

I am using RequireJS 1.0.8. Any idea how to fix the problem? Thanks.


If I look to the source page it looks like:

<script 
      data-main="/~myName/myProject/web/bundles/web/js/main.js?101205021855"       
      src="/~myName/myProject/web/vendor/js/require.js?101205021855">
</script>

So the paths are rights, but on javascript console I get the following message:

GET http://localhost/~myName/myProject/web/app_dev.php/main.js?201205021855 404 (Not Found)

回答1:

Adding to @dgabriel response. You can do it using slice filter,

<script 
        data-main="{{ asset('bundles/web/js/main.js') | slice(0, -3) }}" 
        src="{{ asset('vendor/js/require.js') }}">
</script>


回答2:

  1. Make sure to leave off the '.js' file extension from your assets. It should be data-main="{{ asset('bundles/web/js/main') }}"

  2. Make sure your path to the file is correct.

  3. Make sure there are no javascript errors in main.js



回答3:

That 404 looks like it's coming as a result of 'main' being required somewhere else in your application - it doesn't match the path in your data-main. In that case, it's most likely an issue with your baseUrl or paths config (both of which are different ways to tell RequireJS where your modules are located). In your example, your baseUrl would need to be '/~myName/myProject/web/bundles/web/js'.

You may want to try using https://github.com/hearsayit/HearsayRequireJSBundle. It handles those configuration details for you automatically, and integrates nicely with Assetic.