jQuery doesn't work and I can't use my bootstrap dropdown, custom javascript...
After a npm run dev (or npm run build), app.js file is well created and loads in the browser.
Compilation is done without any error.
I tried to enable .autoProvidejQuery() then npm run dev / npm run build, but nothing changes.
I am using Symfony 4.1.6
Solution found
Change .enableSingleRuntimeChunk() to .disableSingleRuntimeChunk() in webpack.config.js
If you just comment on the line, it works but you have a warning message when you run a npm run dev or npm run build.
package.json
"devDependencies": {
"#symfony/webpack-encore": "^0.22.0",
"bootstrap": "^4.2.1",
"jquery": "^3.3.1",
"popper.js": "^1.14.6",
"webpack-notifier": "^1.6.0"
},
"license": "UNLICENSED",
"private": true,
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production --progress"
},
"dependencies": {
"node-sass": "^4.11.0",
"sass-loader": "^7.1.0"
}
webpack.config.js
var Encore = require('#symfony/webpack-encore');
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 you JavaScript imports CSS.
*/
.addEntry('js/app', './assets/js/app.js')
.addEntry('js/ad', './assets/js/ad.js')
.addStyleEntry('css/app', './assets/css/app.scss')
//.addStyleEntry('css/bootstrap', './assets/css/bootstrap.min.css')
// 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 & 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 Sass/SCSS support
.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// 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();
app.js
const $ = require('jquery');
global.$ = global.jQuery = $;
require('bootstrap');
base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SymBNB - {% block title %}Bienvenue !{% endblock %}</title>
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" href="{{ asset('build/css/app.css') }}">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="sha384-aOkxzJ5uQz7WBObEZcHvV5JvRW3TUc2rNPA7pe3AwnsUohiw1Vj2Rgx2KSOkF5+h" crossorigin="anonymous">
{# <link rel="stylesheet" href="/css/app.css"> #}
{% block stylesheets %}{% endblock %}
</head>
<body>
{% include 'partials/header.html.twig' %}
{% block body %}{% endblock %}
{% include 'partials/footer.html.twig' %}
{#<script src="/js/jquery.min.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>#}
<script src="{{ asset('build/js/app.js') }}"></script>
{% block javascripts %}{% endblock %}
</body>
</html>
Similar topics:
webpack symfony encore jquery third party plugins
Webpack Encore - $ is not defined
If you have enableSingleRuntimeChunk() in your webpack.config.js you need to add <script src="{{ asset('build/runtime.js') }}"></script> in your base template.
There is a Twig helper encore_entry_script_tags() to handle this automatically.
Solution found
Change .enableSingleRuntimeChunk() to .disableSingleRuntimeChunk() in webpack.config.js
If you just comment on the line, it works but you have a warning message when you run a npm run dev or npm run build.
Related
I have several JavaScript files created via Webpack. Besides the general app.js I also have JavaScript files that are only used on certain pages. After the build process, I have included the new JavaScript file included. The JS file is also loaded successfully. But the JavaScript does not run.
What do I have to do to make it work? Or am I already doing something wrong?
Goal run my build/myjs.js file and print console.log('Hello world!');
webpack.config.js
Encore
// …
.addEntry('app', './assets/app.js')
.addEntry('myjs', './assets/scripts/my.js')
// …
build/myjs.js
(self["webpackChunk"] = self["webpackChunk"] || []).push([["myjs"],{
/***/ "./assets/scripts/myjs.js":
/*!********************************!*\
!*** ./assets/scripts/myjs.js ***!
\********************************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__)
=> {
__webpack_require__(/*! core-js/modules/es.array.for-each.js */
"./node_modules/core-js/modules/es.array.for-each.js");
__webpack_require__(/*! core-js/modules/es.object.to-string.js */
"./node_modules/core-js/modules/es.object.to-string.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.for-each.js */
"./node_modules/core-js/modules/web.dom-collections.for-each.js");
__webpack_require__(/*! core-js/modules/es.array.concat.js */
"./node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! core-js/modules/es.promise.js */
"./node_modules/core-js/modules/es.promise.js");
console.log('Hello world!');
// ...
My show.html.twig file where I need the special JavaScript:
{% extends 'test/base.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('build/myjs.js') }}"></script>
{% endblock %}
You have add in your twig file the encore_entry_script_tags() helpers function. As parameter you pass the name of the file which you want to include. In your case myjs.
The same you have to do with CSS files. But then use the encore_entry_link_tags() helper function. With the name from the file as parameter. Dont forget to use addStyleEntry('targetName',source).
You just need to use encore_entry_script_tags function, as shown here.
In your case, it would be something like:
{% extends 'test/base.html.twig' %}
{{ encore_entry_script_tags('myjs') }}
The file will be loaded automatically, and as any JS file will be executed when loaded.
I have a problem with Symfony 5.4 and WebPack yet.
when I want to run the npm run dev-server this one tells me:
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:3000/, http://127.0.0.1:3000/
<i> [webpack-dev-server] Content not from webpack is served from 'F:\Symfo\api-2021\public' directory
<i> [webpack-dev-server] 404s will fallback to '/index.html'
DONE Compiled successfully in 2064ms
and on the page (localhost or 127.0.0.1) I have Cannot GET / and nothing in the console except that I am missing the favicon
my version of npm is: 8.1.2
my webpack.config.js
const 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
*
* 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/app.js')
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')
// 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 & 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())
.configureBabel((config) => {
config.plugins.push('#babel/plugin-proposal-class-properties');
})
// enables #babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
// enables Sass/SCSS support
//.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment if you use React
.enableReactPreset()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
;
module.exports = Encore.getWebpackConfig();
EDIT
this is my Controller
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class AppController extends AbstractController
{
/**
* #Route("/", name="app")
*/
public function index(): Response
{
return $this->render('app/index.html.twig', [
]);
}
}
The template app/index.html.twig
{% extends 'base.html.twig' %}
{% block title %}Hello AppController!{% endblock %}
{% block body %}
<h1>Hello World!</h1>
{% endblock %}
and the base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
{# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
{% block stylesheets %}
{{ encore_entry_link_tags('app') }}
{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
and the app.js
import './styles/app.css';
// start the Stimulus application
import './bootstrap';
console.log('test')
Thank you for your help
I am trying to implement AdminLTE for the AdminCP of my website in Symfony 4. I performed these steps:
Ran composer require kevinpapst/adminlte-bundle ^2.0
Ran cp vendor/kevinpapst/adminlte-bundle/config/packages/admin_lte.yaml config/packages/
Added .addEntry('adminlte', './assets/js/adminlte.js') to webpack.config.js
Modified package.json so it looks like:
This
{
"devDependencies": {
"#fortawesome/fontawesome-free": "~5.1.1",
"#symfony/webpack-encore": "^0.27.0",
"admin-lte": "~2.4.8",
"bootstrap-sass": "^3.3.7",
"bootstrap-select": "^1.13.1",
"daterangepicker": "^3.0.3",
"icheck": "^1.0.2",
"jquery-slimscroll": "^1.3.8",
"bootstrap": "^4.3.1",
"core-js": "^3.0.0",
"jquery": "^3.4.1",
"node-sass": "^4.12.0",
"popper.js": "^1.15.0",
"sass-loader": "^7.0.1",
"webpack-notifier": "^1.6.0"
},
"license": "UNLICENSED",
"private": true,
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production --progress"
},
"dependencies": {
"startbootstrap-blog-home": "^4.2.1"
}
}
Ran yarn install.
Added assets/js/adminlte.js with require('../../vendor/kevinpapst/adminlte-bundle/Resources/assets/admin-lte');
Ran yarn encore dev
The problem now is, the layout doesn't render properly at all. Like, it has the right text from the layout but it doesn't show the layout properly (see the attached screen).
See the problem with the layout here
The template rendered in my controller function of the route contains only this:
{% extends 'admincp/base.html.twig' %}
The admincp/base.html.twig contains this:
{% extends '#AdminLTE/layout/default-layout.html.twig' %}
{% block stylesheets %}
<link rel="stylesheet" href="{{ asset('build/adminlte.css') }}">
{% endblock %}
{% block javascripts %}
<script src="{{ asset('build/adminlte.js') }}"></script>
{% endblock %}
It doesn't throw an error or anything but it doesn't work either. It requests and gets the CSS and JS correctly.
(in case more information is needed, kindly ask and I'll provide it).
In my gruntfile.js I am using bower install to create the necessary script tags in my index.html for all my js libraries. My grunt file entry looks like this:
bowerInstall: {
target: {
src: ['wwwroot/index.html'],
cwd: '',
dependencies: true,
devDependencies: true,
exclude: [],
fileTypes: {},
ignorePath: '',
overrides: {}
}
}
My index.html gets correctly updated from my index.html.tpl as seen here:
<head>
<!-- bower:js -->
<script src="../bower_components/jquery/dist/jquery.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="../bower_components/underscore/underscore.js"></script>
<!-- endbower -->
<!-- bower:css -->
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<link rel="stylesheet" type="text/css" href="wwwroot/app/styles/style.css" />
What I want to happen is to copy all js library files to a specific lib directory, and then link them from there. Can this be accomplished with bower install or is there another grunt plug-in I should be using? The bower-install plugin seems popular but I can't find much documentation for it.
You should try to use grunt-bower along with grunt-bower-install. You can configure bower to install copy files to specific folders. It will look like this:
bower: {
dev: {
dest: 'lib/',
js_dest: 'lib/js',
css_dest: 'lib/styles'
}
}
Then if you run the task:
grunt bower
You will have something like this in your lib folder:
/js
/package1
package1_file1.js
package1_file2.js
/package2
package2.js
/styles
/package1
package1.css
/package2
package2.css
Add a .bowerrc file next to your bower.json. If the file is already in there change its content from:
{
"directory": "bower_components"
}
to
{
"directory": "you/new/lib/path"
}
Re-install your Bower components:
bower install
Then call the Grunt task:
grunt bowerInstall
yo angular install bootstrap files all fine. The index.html file looks like this at the moment:
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
This doesn't include bootstrap.theme.css file.
What is the recommended way of adding this? Do I manually go in there and add it?
The correct way to do it is override you bower.json file to load bootstrap dependencies, and then run grunt wiredep
The bower.json would look like this:
{
"name": "frontend",
"version": "0.0.0",
"dependencies": {
"angular": "^1.3.0",
"json3": "^3.3.0",
"es5-shim": "^4.0.0",
"bootstrap": "^3.2.0",
"angular-cookies": "^1.3.0",
"angular-route": "^1.3.0",
"angular-local-storage": "~0.1.5",
"raty": "~2.7.0",
"kineticjs": "~5.1.0"
},
"devDependencies": {
"angular-mocks": "~1.3.0",
"angular-scenario": "~1.3.0"
},
"appPath": "app",
"overrides": {
"bootstrap": {
"main": [
"less/bootstrap.less",
"dist/css/bootstrap.css",
"dist/css/bootstrap-theme.css",
"dist/js/bootstrap.js",
"dist/fonts/glyphicons-halflings-regular.eot",
"dist/fonts/glyphicons-halflings-regular.svg",
"dist/fonts/glyphicons-halflings-regular.ttf",
"dist/fonts/glyphicons-halflings-regular.woff"
]
}
}
}
Source: https://github.com/yeoman/generator-angular/issues/965#issuecomment-68548259
Do the following
bower install bootstrap-css --save
Add it manually below the other .css include if it's locally available on your system (e.g. in bower_components/).
If the file is not locally available I'd add it right above the <!-- Place favicon.ico ... --> otherwise it might break your grunt build and/or grunt serve because of bower trying to minify the file.
The same goes with Google Font imports, place them above the <!-- Place favicon.ico ... --> otherwise bower will try to minify it (under htmlmin options in Gruntfile.js).
Here you can read some more about the subject.