简体   繁体   中英

What is the best way to include jQuery for symfony project using composer and assets

I have jQuery installed with composer.

Now jQuery is in vendor/components/jquery directory.

I've tried to include that in /app/config/config.yml

assetic:
    debug:          "%kernel.debug%"
    use_controller: false
    filters:
        cssrewrite: ~
    assets:
        jquery: %kernel.root_dir%/../vendor/components/jquery/jquery.min.js

If I run the command:

php app/console assetic:dump

I get

[RuntimeException]                                                                                                              
  The source file "/home/user/project/app/current/app/../web/vendor/components/jquery/jquery.min.js" does not exist.

Cause assetic is still looking in the /web/ directory which is wrong. How can I change it so it will look in the /vendor/ directory? Also I don't want to put the jquery files in the public bundle folder cause that would brake all the sense of getting the right versions of vendor libraries via composer.

I'm not a big fan of installing jquery in the vendor directory in Symfony, as it's not a PHP library. Composer and vendor directory should only be used for PHP dependencies. You should separates the frontend part from the backend part. All the js, css and other assets should go somewhere else.

Therefore you have 2 options:

  1. If you want to have separate resources per bundle, then put your resources you use for the frontend in the public directory of your bundle: for example put your jquery.min.js in the Resources/public/js folder of your bundle.

Then run the command php app/console assets:install . this will copy your js files to the web/bundles/yourbundle/js/ directory.

Finally use <script type="text/javascript" src="{{ asset('yourbundle/js/jquery.min.js') }}"></script> in your twig file to add jquery.

  1. If you have common resources for all your bundles, put your resources directly in the web folder, for example: web/js , web/css , web/img ... And then use <script type="text/javascript" src="{{ asset('js/jquery.min.js') }}"></script> in your twig template.

While following the links from comments and retrying other answers it was pretty easy. Everything missing was

composer require robloach/component-installer

more information about robloach/component-installer

Then add this line manually to composer.json

"config": {
    #...
    "component-dir": "web/assets",
    #...
},

Assumed that you already have

composer require components/jquery

You might have to rerun the command

composer install

Now it will create a directory /web/assets/jquery with all the files which will be easy to include.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM