简体   繁体   中英

Webpack + Symfony encore - how to add libraries

I am quite new in using webback and encore, so I don't know exactly which is the approach to handle this.

I have a website with a few js files, and it uses jQuery and Bootstrap. I want to create a unique minified js file using webpack.

I've been able to successfully do it following the examples at Symfony website, so I am able to just include one app.js and encore builds the dependencies correctly.

There are some javascript libraries that are not used in my app.js but will be used in some javascript code inlined in the website, like for example the PhotoSwipe.

Currently, I am requiring the PhotoSwipe library inside my main.js file, although this file doesn't use this library.

// Resources/public/js/main.js
import PhotoSwipe from 'photoswipe';
import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default';

So, how can I tell encore to add this library into the builded app.js without having to add it in my main.js?

I've tied to add it in webpack.config.json

.addEntry('app', [
    './src/AppBundle/Resources/public/js/main.js',
    'photoswipe',
    'photoswipe/dist/photoswipe-ui-default'
])

If I check the app.js generated I can see the code has been added to app.js, but when I try in my html code to call Photoswipe I get the error Uncaught ReferenceError: PhotoSwipe is not defined

I guess that this is as the libraries are confined inside the js file, and I should add some kind of export to be accessible, I don't know, as I've said, I am very new in this ;)

This is how I managed my libraries:

// Resources/public/js/myCustomScript.js
const PhotoSwipe = require('photoswipe.js)';
const PhotoSwipeUI_Default = require ('photoswipe/dist/photoswipe-ui-default');
[...] // do PhotoSwipe stuff

And in your webpack.config.json only:

.addEntry('myCustomScript', './src/AppBundle/Resources/public/js/myCustomScript.js')

Then in the templates that needs this script :

<script type="text/javascript" src="{{ asset('build/myCustomScript.js') }}"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM