Search code examples
jquerycdnyarnpkgsymfony5webpack-encore

Yarn add Complete Jquery


On a new symfony 5.1 application whenever i use yarn add jquery the most common methods are not defined.
I assume yarn is adding the slim version which is not what I want.
I am not running yarn add jquery-slim

For instance .ajax(), .addClass(), .css() are not available.
When I use it from CDN it works normally.

What am I doing wrong?

This is some console output. I am able to retrieve the element but not to use .addClass method. console output

This is my App.js

/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you import will output into a single css file (app.scss in this case)
import '../css/app.scss';

require('bootstrap');

// Need jQuery? Install it with "yarn add jquery", then uncomment to import it.
import $ from 'jquery';

console.log('Webpack Loaded');

My package.json is as follows:

{
    "devDependencies": {
        "@symfony/webpack-encore": "^0.30.0",
        "core-js": "^3.0.0",
        "node-sass": "^4.14.1",
        "regenerator-runtime": "^0.13.2",
        "sass-loader": "^8.0.0",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    },
    "dependencies": {
        "bootstrap": "^4.5.2",
        "copy-webpack-plugin": "^6.0.4",
        "jquery": "3.5.1",
        "popper.js": "^1.16.1"
    }
}

Solution

  • Are you using Google Chrome? If so, you might be hooking into the Console Utilities API, which treats $ as an alias for document.querySelector() -- but only if you don't already have a global $ set.

    You can fix this issue like so:

    import $ from "jquery";
    window.$ = $;
    

    The second line explicitly sets $ to the global window object.