使用Webpack Encore定义全局函数,Twig模板调用报未定义错误
Got it, let's break down why this error is popping up and fix it right away. The core problem here boils down to how Webpack handles module scoping and global variables in the browser environment.
Why the Error Happens
When you use global.enableAjaxModal in your app.js, you might assume this attaches the function to the browser's global scope (which is the window object). But Webpack wraps every module in its own isolated scope—so the global variable here refers to Webpack's internal module-level global, not the browser's actual window object. That's why your template's script can't find the function later.
Solution 1: Attach the Function Directly to window (Simplest Fix)
Modify your assets/js/app.js to assign the function straight to window instead of global:
import {$, jQuery} from 'jquery'; import 'modaal/dist/js/modaal'; import 'foundation-sites'; // Attach to window to make the function accessible globally window.enableAjaxModal = function enableAjaxModal(selector) { $(selector).modaal({ type: 'ajax' }) };
Solution 2: Double-Check Script Loading Order
You already have the app.js script loaded before your custom script in the Twig template, which is correct. Just make sure there's no async or defer attribute on the app.js tag that would delay its execution (your current code doesn't include this, so this is just a quick sanity check).
Bonus: Confirm jQuery Availability
Since you're using autoProvidejQuery() in your Webpack config, $ and jQuery should be globally available automatically. If you ever run into issues with jQuery not being found, you could explicitly attach it to window too (though Encore's auto-provision should handle this for you).
Test the Fix
After updating app.js, recompile your assets with:
npm run dev # Or use watch mode to auto-recompile on changes: npm run watch
Refresh your page, and the enableAjaxModal function should now work as expected in your template's script.
内容的提问来源于stack exchange,提问作者ibousfiha

