javascript - Javascript文件在symfony twig中不起作用
问题描述
在我的 symfony 项目中,我的 css 链接良好,但我的 javascript 无法正常工作,我找不到原因。我想我错过了一些愚蠢的事情......!自从我运行 Sass 以来,我一开始就尝试使用 encore webpack,但我放弃并切换到 classi src=""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{# Run `composer require symfony/webpack-encore-bundle`
and uncomment the following Encore helpers to start using Symfony UX #}
{% block stylesheets %}
{# {{ encore_entry_link_tags('app') }}#}
{# {{ encore_entry_script_tags('app') }}#}
<link rel="stylesheet" href="{{ asset('bundles/mercuryseriesflashy/css/flashy.css') }}">
<link rel="stylesheet" href="{{ asset('./build/app.css') }}">
{% endblock %}
{% block javascripts %}
{# {{ encore_entry_script_tags('app') }}#}
<!-- Flashy depends on jQuery -->
{% endblock %}
</head>
<body>
{% block navbar %} {% include 'inc/navbar.html.twig'%}{% endblock %}
{% block body %}{% endblock %}
{% block footer %}{% endblock %}
<script src="{{ asset('./build/app.js') }}"></script>
<script src="//code.jquery.com/jquery.js"></script>
</body>
</html>
/*
* 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.scss in this case)
import './styles/app.scss';
import './bootstrap';
// start the Stimulus application
const logoMenu = document.querySelector('.logoMenuImg');
const contItems = document.querySelector('.contItems');
const arrItems = document.querySelectorAll('.items');
console.log(logoMenu);
console.log(contItems);
console.log(arrItems);
console.log('arrItems');
alert('hello world');
谢谢您的帮助
ps:在inspector中它是空白的,没有错误
解决方案
如果你使用encore_entry_script_tags
我假设你已经在你的 webpack 配置中添加了你的 JS 文件?我看到您正在使用资产,如果您在 Symfony 4.4 及更高版本中,请删除它,它已被弃用。使用 Webpack 安可。
let Encore = require('@symfony/webpack-encore');
let CopyWebpackPlugin = require('copy-webpack-plugin');
//let TerserPlugin = require('terser-webpack-plugin');
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')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.addEntry('app', './assets/js/app.js')
.enableSingleRuntimeChunk()
;
module.exports = Encore.getWebpackConfig();
并运行npm run build
或yarn encore <env>
查看文档:https ://symfony.com/doc/current/frontend.html
推荐阅读
- angular - 无法在 jsPDF 的 addImage() 函数上为多个页面添加边距
- html - 在 HTML 源页面 (Firefox) 中标记为红色的 & 号实体
- xamarin - 如何以xamarin形式在相机屏幕上设计框架边界
- python - uwsgi + nginx部署下无法使用tensorflow模型
- r - 我不能使用 R CMD BUILD 因为我在 R\R-3.4.0\bin 中没有构建文件
- swift - 在 Swift 中如何编写一个将 [String:[Int]] 转换为 [String:Int] 的函数
- ruby-on-rails - 你可以使用带有 JS 框架(如 Vue)的 Rails 引擎吗
- python - 多个计时器一次
- c# - 使用 Windows 服务“登录为”用户作为 Web 请求的 NetworkCredentials
- android - adb 远程拉文件到桌面