Событие Symfony, webpack, on click выполняется дважды только в среде prod

#javascript #php #symfony #webpack

#javascript #php #symfony #webpack

Вопрос:

Я использую symfony/framework-bundle 5.0.5 , и "symfony/webpack-encore-bundle": "dev-master" когда я разрабатываю код в среде разработки, все было правильно, но при переключении проекта на среду prod я столкнулся со странным поведением, мое событие on lick выполнялось два раза, возможно, какой-то двойной, включая js-скрипт, который я не понимаю, когда я вернулся в среду разработки, проблема исчезла. Как правильно использовать веб-пакет в среде symfony в среде prod env?

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('index/js/index.min', './assets/js/index/index.js')
    .addEntry('index/js/awin.min', './assets/js/index/awin.js')
    .addEntry('index/js/adtraction.min', './assets/js/index/adtraction.js')
    .addEntry('index/js/adrecord.min', './assets/js/index/adrecord.js')
    .addEntry('index/js/tradeDoubler.min', './assets/js/index/tradeDoubler.js')
    .addEntry('index/js/hover_menu.min', './assets/js/index/hover_menu.js')
    .addEntry('index/js/brand_list.min', './assets/js/index/brand_list.js')
    .addEntry('index/js/admin_shop_rule_list.min', './assets/js/index/admin_shop_rule_list.js')
    .addEntry('index/js/resource_shop_list.min', './assets/js/index/resource_shop_list.js')
    .addEntry('index/js/statisticsMonitoring.min', './assets/js/index/statisticsMonitoring.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 amp; 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
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    // enables Sass/SCSS support
    .enableSassLoader()
    .addStyleEntry('index/css/index.min', './assets/css/app.scss')

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

    // uncomment to get integrity="..." attributes on your script amp; 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')
;

module.exports = Encore.getWebpackConfig();
  

config/packages/prod/webpack_encore.yaml

 webpack_encore:
#     Cache the entrypoints.json (rebuild Symfony's cache when entrypoints.json changes)
#     Available in version 1.2
    cache: true
  

config/packages/webpack_encore.yaml

 webpack_encore:
    # The path where Encore is building the assets - i.e. Encore.setOutputPath()
    output_path: '%kernel.project_dir%/public/build'
  

в моем базовом шаблоне twig есть скрипт только для fosjsrouting

 {% block javascripts %}

    <script src="{{ asset('bundles/fosjsrouting/js/router.min.js') }}"></script>
    <script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>

{% endblock %}
  

и мой дочерний шаблон, с которым я столкнулся с двойным щелчком

 {% extends 'base.html.twig' %}
//...///
{% block javascripts %}
    {{ parent() }}
    {{ encore_entry_script_tags('index/js/resource_shop_list.min') }}

    <script>
        function getJSonObject(value) {
            return $.parseJSON(value.replace(/amp;quot;/ig, '"'));
        }

        let th_keys = getJSonObject("{{ dataTbaleKeys ? dataTbaleKeys|json_encode() : "{}" }}");
        let for_prepare_defs = getJSonObject("{{ dataTbaleKeys ? dataTbaleKeys|json_encode() : "{}" }}");

    </script>

{% endblock %}
  

и мой assets/js/index/resource_shop_list.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.css in this case)
import '../../css/app.scss';
import * as dt_bs4 from 'datatables.net-bs4'
import * as fh_bs from 'datatables.net-fixedheader-bs4';
import * as r_bs from 'datatables.net-responsive-bs4';

require('@fortawesome/fontawesome-free/css/all.min.css');
require('datatables.net-dt/css/jquery.dataTables.min.css');
require('datatables.net-fixedheader-bs4/css/fixedHeader.bootstrap4.min.css');
require('datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css');

require('@fortawesome/fontawesome-free/js/all.js');

const $ = require('jquery');
global.$ = global.jQuery = $;
// import 'popper.js';
require('bootstrap');


document.addEventListener("DOMContentLoaded", function () {
    console.log("resource shop list!");
    const body = $('body');
    const app_rest_admin_resourceshops_shopreloading = window.Routing.generate('app_rest_admin_resourceshops_shopreloading');
    var table;
    body.on('click', '.resource_reloading button', function () {
        let current = $(this);
        console.log(current);

        let shopName = current.data('shopName');

        reloadingShop(shopName);
    });

    // ...//
  

Я дважды проверил, я критикую событие только один раз, и в среде разработки оно работает правильно.
Для prod env на сервере я выполнил

 php bin/console c:c amp;amp; yarn encore production amp;amp; chmod 777 -R
 var/cache/ var/log/
  

с результатом

 Done in 13.51s.
  

Как это разрешить?

Ответ №1:

Вы можете изменить прослушиватель jQuery с on() на one() на, чтобы предотвратить дублирование событий:

 body.one('click', '.resource_reloading button', function () {
    // ...
});