📜 ⬆️ ⬇️

WebJars + RequireJS

Good day, readers Habr!
In this article, I hasten to tell you (albeit late) about what WebJars is by the example of an application in the Play Framework.

image In almost any web application can not do without third-party javascript-libraries. The easiest way to add them is to download and add to the project, and also add the file to the git repository. The solution is good, but for me personally, the presence of any static in the project is a bit annoying. There is another method: specify a link to external hosting js-libraries such as google, yandex. In principle, this is an option, but in my practice there were cases when it was necessary to continue development and access to the Internet left much to be desired or it did not exist at all, as a result, the client part did not function. The most suitable solution seems to me to add the js library as a dependency in a project, with a similar approach you could encounter in Ruby on Rails.

Closer to the point

We have a web application written in java-based language and we need to add a couple of javascript libraries to it, just for this occasion, WebJars are perfect for us.
')
WebJars - a set of libraries, each of which contains a JS library and / or CSS modules.

Full list of libraries can be found here . Each of them has several versions that correspond to the version of the js-library. All WebJars are available on the Maven repositories.

In this example, I will describe how WebJars is in the Play Framework application. Descriptions of adding WebJars to other frameworks can be found here .

Getting started

In order to add WebJar it is enough to add a new dependency to the project.

For example:

libraryDependencies ++= Seq( cache, ws, "org.webjars" %% "webjars-play" % "2.3.0-2", "org.webjars" % "requirejs" % "2.1.14-3", "org.webjars" % "requirejs-domready" % "2.0.1-2", "org.webjars" % "jquery" % "2.1.1", "org.webjars" % "bootstrap" % "3.2.0-2" ) 


If you compile the project, you can find the new web-modules folder in the target / web directory. It contains the files added to the js and css project.

You can access them from view in the old way @ routes.Assets.at (“lib / requirejs / require.js”), but for this you need to know the full path. Another kosher way to use ready-made WebJars controllers. To do this, add a new route to conf / routes specifically for WebJars:

 GET /lib/*file controllers.WebJarAssets.at(file) 


And to access them from the view, we can use another method from WebJars WebJarAssets.locate. The specified method itself searches for the required file in the directory with WebJars. As a result, we obtain:

 <link rel="stylesheet" href="@routes.WebJarAssets.at(WebJarAssets.locate("bootstrap.min.css"))"> 


What on the html page will look like

 <link rel="stylesheet" href="/lib/bootstrap/3.2.0-2/css/bootstrap.min.css"> 


Convenient is not it? But that is not all.

RequireJS

Surely you have already heard about the charms of this wonderful js-framework, so I will not grovel on this topic.

WebJars contains a mechanism for more convenient integration with RequireJS. If you go to the target / web / web-modules / main / webjars / lib / jquery directory, you will find the webjars-requirejs.js file with the contents.

 /*global requirejs */ // Ensure any request for this webjar brings in jQuery. requirejs.config({ paths: { "jquery": webjars.path("jquery", "jquery") }, shim: { "jquery": { "exports": "$" } } }); 


Each WebJar has a file with a config for RequireJS. To get a common config, create a new view named requireJsConfig.

 @Html(org.webjars.RequireJS.getSetupJavaScript(routes.WebJarAssets.at("").url)) 


Add a new action to the Application controller.

 import play.api.cache.Cached import views._ import play.api.Play.current def requireJsConfig = Cached("require_js_config") { Action { Ok(html.requireJsConfig()).as("application/javascript") } } 


We cache the result of the execution, since its contents will change only when the WebJars used in the project are added / deleted. We also mark the result as application / javascript to explicitly point to the content as javascript.

Add a new route:

 GET /files/config.js controllers.Application.requireJsConfig 


Fun for url prescribe as a static js-file.

Checking what happened, in the browser, go to url http: // localhost: 9000 / files / config.js

 var webjars = { versions: {"requirejs-domready":"2.0.1","requirejs":"2.1.14-3","bootstrap":"3.2.0-2","jquery":"2.1.1"}, path: function(webJarId, path) { console.error('The webjars.path() method of getting a WebJar path has been deprecated. The RequireJS config in the ' + webJarId + ' WebJar may need to be updated. Please file an issue: http://github.com/webjars/' + webJarId + '/issues/new'); return ['/lib/' + webJarId + '/' + webjars.versions[webJarId] + '/' + path]; } }; var require = { callback: function() { // Deprecated WebJars RequireJS plugin loader define('webjars', function() { return { load: function(name, req, onload, config) { if (name.indexOf('.js') >= 0) { console.warn('Detected a legacy file name (' + name + ') as the thing to load. Loading via file name is no longer supported so the .js will be dropped in an effort to resolve the module name instead.'); name = name.replace('.js', ''); } console.error('The webjars plugin loader (eg webjars!' + name + ') has been deprecated. The RequireJS config in the ' + name + ' WebJar may need to be updated. Please file an issue: http://github.com/webjars/webjars/issues/new'); req([name], function() {; onload(); }); } } }); // All of the WebJar configs requirejs.config({"paths":{"requirejs-domready":["/lib/requirejs-domready/2.0.1/domReady","domReady"]}}) requirejs.config({"paths":{}}) requirejs.config({"paths":{"bootstrap":["/lib/bootstrap/3.2.0-2/js/bootstrap","js/bootstrap"],"bootstrap-css":["/lib/bootstrap/3.2.0-2/css/bootstrap","css/bootstrap"]},"shim":{"bootstrap":["jquery"]}}) requirejs.config({"paths":{"jquery":["/lib/jquery/2.1.1/jquery","jquery"]},"shim":{"jquery":{"exports":"$"}}}) } } 


This script configures RequireJS in the way we need it and must precede RequireJS itself.

The final

Let's create a small coffescript file (forgive me if I upset someone with this, but I'm tired of pure javascript) in the app / assets / js / main.coffee directory.

 require ['jquery','requirejs-domready!'],-> $('body').text 'Success' 


And in the view that interests us, add.

 <script type="application/javascript" src="@routes.Application.requireJsConfig()"></script> <script data-main="@routes.Assets.at("js/main.js")" src="@routes.WebJarAssets.at(WebJarAssets.locate("require.min.js"))"></script> 


We start and see that all the necessary javascript files were loaded and the code was executed.

Total

In this example, we learned about the capabilities of WebJars. From myself I will add that I have not found anything cardinally innovative, but still they facilitate frontend development.

Source: https://habr.com/ru/post/241515/


All Articles