webpack - 在模板页面上使用 webpack 中定义的函数
问题描述
我正在使用webpack
with 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
解决方案
您可以像这样将它添加到窗口并在模板中的任何位置使用它:
function enableAjaxModal (elem) {
// your code
}
window.enableAjaxModal = enableAjaxModal ;
推荐阅读
- javascript - d3 V4 中尝试在 AlbersUSA 上使用 projection.center() 时出现“不是函数”错误
- apache-kafka - 通过 Kafka Connect 的 /connectors/ 保护敏感信息
/配置 API - tiddlywiki - 无法自动生成链接列表
- flowtype - 流程:为什么它抱怨字符串为空/未定义?
- java - 使用 indexOf() 方法,有没有办法让我返回按字母顺序排列的字符串中的第一个索引?爪哇
- java - 有没有办法使用 Gson/Jackson 将 Javolution Struct 对象转换为 json?
- protractor - 并行运行数据驱动测试的量角器
- angular - 将 routerLink 与函数调用一起使用
- r - R - 如何使用 system() 或 system2() 执行 PowerShell cmds
- java - 在没有eclipse的情况下安装Java库