首页 > 解决方案 > 在模板页面上使用 webpack 中定义的函数

问题描述

我正在使用webpackwith encore,我正在尝试在 webpack 条目中定义一个可重用的函数并在模板上重用它

资产/js/app.js:

import {$, jQuery} from 'jquery';
import 'modaal/dist/js/modaal';
import 'foundation-sites';

global.enableAjaxModal = function enableAjaxModal(selector) {
    $(selector).modaal({
        type: 'ajax'
    })
};  

webpack.config.js:

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

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .addStyleEntry('css/app', './assets/css/global.scss')
    .enableSassLoader()
    .autoProvidejQuery()
    .addEntry('js/app', './assets/js/app.js')
;

module.exports = Encore.getWebpackConfig();

twig_template_page:

<script src="{{ asset('build/js/app.js') }}"></script>
<script type="text/javascript">
    enableAjaxModal('.modaal-new-experience')
</script>

我越来越:

Uncaught ReferenceError: enableAjaxModal is not defined

标签: webpackwebpack-encore

解决方案


您可以像这样将它添加到窗口并在模板中的任何位置使用它:

function enableAjaxModal (elem) {
    // your code
}

window.enableAjaxModal = enableAjaxModal ;

推荐阅读