简体   繁体   English

Webpack + Symfony再次加入 - 如何添加库

[英]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. 我是使用webback和encore的新手,所以我不知道究竟是哪种方法来处理它。

I have a website with a few js files, and it uses jQuery and Bootstrap. 我有一个带有几个js文件的网站,它使用jQuery和Bootstrap。 I want to create a unique minified js file using webpack. 我想使用webpack创建一个独特的缩小的js文件。

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. 我已经能够按照Symfony网站上的示例成功地做到这一点,所以我能够只包含一个app.js和encore正确构建依赖项。

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. 我的app.js中没有使用一些javascript库,但会在网站内嵌的一些javascript代码中使用,例如PhotoSwipe。

Currently, I am requiring the PhotoSwipe library inside my main.js file, although this file doesn't use this library. 目前,我需要在main.js文件中使用PhotoSwipe库,尽管此文件不使用此库。

// 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? 那么,我如何告诉安可将这个库添加到构建的app.js中而不必将其添加到我的main.js中?

I've tied to add it in webpack.config.json 我已将其添加到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 如果我检查生成的app.js,我可以看到代码已添加到app.js,但是当我尝试使用我的html代码调用Photoswipe时,我得到错误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 ;) 我猜这是因为库被限制在js文件中,我应该添加某种导出才能访问,我不知道,正如我所说的,我是非常新的;)

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: 仅在您的webpack.config.json

.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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