Webpack + Symfony encore - how to add libraries - javascript

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>

Related

Including bundled webpack file in webpack build

I have a webpack bundled widget that I pack into a single file using webpack, and can use as follows:
<script type="text/javascript" src="my-bundle.js"></script>
<script type="text/javascript">
(function() {
MyBundle.render();
}) ();
</script>
This works fine, but I want to use this widget in my main Rails app. So I've copied the my-bundle.js file into my main project directory and required it.
When I run webpack on my main app, I can see that the code in my-bundle is being included in the resulting js file, but I cannot access the code. i.e. calling MyBundle gives a not defined error.
How can I access it?
EDIT - it looks like I can just use script-loader to run the my-bundle.js file once (which defines a MyBundle function). This doesn't feel like the best way to do it though

Including external (hosted) javascript files in Angular2

I'm trying to add an external js file into my Angular2 project by adding the record to my angular-cli.json file.
I've added a file to the [scripts] array as below:
"scripts": ["https://as-identitydemo--c.na50.visual.force.com/resource/1495420277000/salesforce_login_widget_js"],
all the other posts that i've read refer to using this format for something that's either hosted locally, or installed in the node_modules etc..
How can I include an external js library and utilize that in my project?
You should import the library in your index.html in the head tag.
Second you have to make the library visible to your Angular project. That means you need the typings. You can either search https://github.com/DefinitelyTyped
for already existing types or add the types to the typings.d.ts file.
Example:
In your page (outside of the Angular app) you might have a javascript global variable:
var testVar = 'testvalue';
Then in the typings.d.ts you can make this variable globally accessible by adding
declare var testVar:string;
Then you can access this variable in the whole Angular project like that:
console.log(testVar);
The same you can do with functions in external libraries.
Here is a Plunk that shows that (without having a typings file). Hope this helps.

Using laravel mix to include js dependencies

i can't really get my js libraries to work , some time ago i decided to have a separate js file for every library i use (so i have a jquery.js file and a bootstrap.js file included in my layout) ,everything was working just fine until i had to add jquery-ui to this chaos , and got this error
Uncaught TypeError: $(...).slider is not a function
until i loaded ,jquery and jquery-ui in the same file .The problem is i dont want to include jquery ui everywhere i include jquery , beacuse i only use it in 2 pages. Below i will put my code :
jquery-ui.slider.js:
require('jquery-ui/ui/widgets/slider');
require('./components/carFilter.js');
app.js:
window.$ = window.jQuery = require('jquery');
require('./bootstrap');
webpack.mix.js:
mix.js('resources/assets/js/app.js', 'public/js')
mix.js('resources/assets/js/jquery-ui.slider.js', 'public/js');
I am using the following npm modules :
bootstrap-sass
jquery
jquery-ui
I ended up by just creating a file where i require jquery,bootstrap.js and then i require this file in a specific file for the two pages...
Below its the code:
app.js
window.$ = window.jQuery = require('jquery');
require('./bootstrap');
page.js
require('./app.js')
require('jquery-ui/ui/widgets/slider');
It seams that now it is working ,even if now i have to include a js file in all the views...Question its still open , i hope somone have a beter idea .
I think laravel-mix only serves the purpose when you have small sites with pages that all include the same app.js & app.css files.
When you have complex portal with multiple pages that have different set of frontend "plugins" you have to split your entries & generate a table of dependencies automatically.
After a lot of time searching I've come to the conclusion that the best approach would be switch to webpack-encore from Symfony.
You can read more about it's capabilities here Webpack Encore Official Documentation.
Now the question is how to embed it to Laravel? It's quite easy, I've just reverse engineered the Symfony's PHP bundle for that and here is the result:
https://github.com/ntpages/laravel-encore
Now you just have to include you're dependency in the page entry and it's all handled automatically.
I think you should load jquery-ui when a condition is met, like:
if (window.loadJQueryUI) {
require('jquery-ui');
}
And you need to initialize loadJQueryUI for the two pages, like this:
<script type="text/javascript">
window.loadJQueryUI = true;
</script>

Import non-module vendor script in webpack

I'm building an app with the AirConsole JS service. AirConsole only provides their library as a .js file you would include in your page with the usual:
<script type="text/javascript" src="https://www.airconsole.com/api/airconsole-1.6.0.js"></script>
However, I'm using Webpack and would like to import the script into my other JS files. I have tried a few methods with no luck:
Create an entry file named vendor which imports the airconsole.js file. This creates a vendor.bundle.js file which I can include on my page
Add the AirConsole path to my index entry point so the script is included in the bundle.js file. With this method I can verify the AirConsole code is included in the bundle.js file but attempting to create a new instance of AirConsole results in AirConsole is undefined
Am I on the right track with these methods? If not, what is the recommended way to import a non-module .js file?
The best way is by an action which we call "shimming". You can check out our new docs page for information. There are a few different ways to do on it (that depend on the needs) for your non-module.
https://webpack.js.org/guides/shimming/

how to use webpack to load CDN or external vendor javascript lib in js file, not in html file

I am using react starter kit for client side programming. It uses react and webpack. No index.html or any html to edit, all js files. My question is if I want to load a vendor js lib from cloud, how to do I do that?
It would be easy to do that in a html file. <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
However, in js file, it only uses npm installed packages. How can I import the above lib with no html file? I tried import and require, they only work for local files.
update 10/21/15
So far I tried two directions, neither is ideal.
#minheq yes there is a html file sort of for react start kit. It is html.js under src/components/Html. I can put cloud lib and all its dependencies there like this:
<div id="app" dangerouslySetInnerHTML={{__html: this.props.body}} />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
<script src="/app.js"></script>
<script dangerouslySetInnerHTML={this.trackingCode()} />
</body>
Good news is it works, I don't need do anything else in js file, no import or require. However, now I have two jquery libs loaded in different ways. One in here, the other through npm and webpack. I wonder it will give me trouble later. The react-routing I use give me 'undefined variable' error if I type a none home path in browser window due to the server side loading I guess. So this solution is not very good.
Use webpack externals feature. This is documented as: link. "You can use the externals options for applications too, when you want to import an existing API into the bundle. I.e. you want to use jquery from CDN (separate tag) and still want to require("jquery") in your bundle. Just specify it as external: { externals: { jquery: "jQuery" } }."
However, the documentation I found a few places are all fussy about how to do this exactly. So far I have no idea how to use it to replace <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script> in html.
externals is not intended to let you do this. It means "don't compile this resource into the final bundle because I will include it myself"
What you need is a script loader implementation such as script.js. I also wrote a simple app to compare different script loader implementations: link.
var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
$('body').html('It works!')
});
You can create a script tag in your JS as
$("body").append($("<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>"))
There is one html file that is definitely being used to serve to users with your js bundle attached. Probably you could attach the script tag into that html file
Use webpack's externals:
externals allows you to specify dependencies for your library that are
not resolved by webpack, but become dependencies of the output. This
means they are imported from the environment during runtime.
I have looked around for a solution and most of all proposals were based on externals, which is not valid in my case.
In this other post, I have posted my solution: https://stackoverflow.com/a/62603539/8650621
In other words, I finished using a separate JS file which is responsible for downloading the desired file into a local directory. Then WebPack scans this directory and bundles the downloaded files together with the application.

Categories

Resources