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 %}
CodePudding user response:
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.
CodePudding user response:
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).