phpjquerysymfony4webpack-encore

How to make jQuery work externally with Symfony Webpack Encore?


I'm following a tutorial on how to create a website with Symfony (so I'm new at this) on a french website, GraphikArt. I'm currently at the "Symfony Encore" part and I can't make it work when I have to require jQuery in my JS file while it's on my Twig file.

I'm working with Symfony 4.3.3 and Yarn 1.17.3. As the guy showed, I tried to make it work externally with that part at the end of my webpack.config.js :

var config = Encore.getWebpackConfig();

config.externals.jquery = 'jQuery';

module.exports = config;

I also tried some solutions foundable on this site but nothing seems to work.

My current files :

webpack.config.js

var Encore = require( '@symfony/webpack-encore' );

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if ( ! Encore.isRuntimeEnvironmentConfigured() ) {
    Encore.configureRuntimeEnvironment( process.env.NODE_ENV || 'dev' );
}

Encore
// directory where compiled assets will be stored
    .setOutputPath( 'public/build/' )
    // public path used by the web server to access the output path
    .setPublicPath( '/build' )
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry( 'app', './assets/js/app.js' )
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps( ! Encore.isProduction() )
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning( Encore.isProduction() )

    // enables @babel/preset-env polyfills
    .configureBabel( () => {
    }, {
        useBuiltIns: 'usage',
        corejs: 3
    } )

    // enables Sass/SCSS support
    .enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    .autoProvidejQuery()

// uncomment if you use API Platform Admin (composer req api-admin)
//.enableReactPreset()
//.addEntry('admin', './assets/js/admin.js')
;

var config = Encore.getWebpackConfig();

config.externals.jquery = 'jQuery';

module.exports = config;

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 require will output into a single css file (app.css in this case)
require( '../css/app.css' );

// Need jQuery? Install it with "yarn add jquery", then uncomment to require it.
var $ = require( 'jquery' );
global.$ = global.jQuery = $;

require( 'select2' );

console.log( 'Hello Webpack Encore! Edit me in assets/js/app.js' );

base.html.twig JavaScript part

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
{{ encore_entry_script_tags( 'app' ) }}

As the tutorial shows, I want to use jQuery in app.js while it is linked in the base.html.twig file.

My problem is that when I save any change in the app.js, I receive this :

Error: ./assets/js/app.js
Error: Can't resolve 'jquery' in 'C:\wamp\www\symfony4\assets\js'

How is it possible for the tutorial (and the solutions online too) to work for others but not for me?

Solution

In the webpack.config.js file, instead of :

var config = Encore.getWebpackConfig();

config.externals.jquery = 'jQuery';

module.exports = config;

and before the .autoProvidejQuery() line, write :

.addExternals(
    {
        jquery: 'jQuery'
    }
)

Moreover, the problem was I wasn't using the proper command line. Use yarn encore dev.


Solution

  • You get this error because you are trying to import things like jQuery into files that are processed by Webpack (require('jquery')) without actually having the dependencies in your node_modules folder.

    In order to fix that you will need to either: