Add a JavaScript module
This video provides a walk-through for developing a simple JS module that provides the greeting “Hello World”.
Who is this video for?
- Developers
Steps
- Create a module
- Create a
requirejs-config.js
and a JavaScript module file - Create layout update for adding a template that enables the JS module
- Create template file
- Add the module and test it
Video content
Transcript
Create a new JavaScript to module.
Magento 2 uses RequiredJS as a tool to define the JavaScript module structure. However, in addition to RequireJS, Magento 2 also has its own unique way to execute JavaScript code. You’ll see this in the example we’re using.
We will develop a very simple JavaScript module that only provides the greeting “Hello World.” It will illustrate how Magento 2 works with JavaScript files executing the code and passing parameters inside of a script.
The steps we’ll need to take are one, create a new module. Two, create a requiredjs-config.js and a JavaScript module file. Three, create a layout update to add a template that will enable the JavaScript module. Four, create a template file. Five, add the module and test it. Let’s go through each step. One, create a new module.
We will create a new module called Learning_JS.
Now create two files, registration.php and Etsy module xml.
Step two, create a requiredjs-config.js and a JavaScript module file.
Next we’ll create a view folder.
Add the file view front end requiredjs-config.js.
Then add a JavaScript module.
And finally add the file front-end web js, hello.js.
Step three, create a layout update to add a template that will enable the JavaScript module. First, we need to create the layout folder.
And then add the file catalog_product_view.xml.
Step four, create a template file.
Now we’ll create the template that will enable the JavaScript.
In the templates directory, add the file helo.phtml. This code enables our module. It may look a little strange to those who have used RequiredJS before. As mentioned earlier, Magento 2 has its own unique process for executing JavaScript code. One way is to use the data-mage-init attribute which takes a JSON object as a parameter, as can be seen in this example. Each key of that object corresponds to the module and the value is a config. In this case, the JavaScript module should return a function with two parameters, config and element. Again, this can be seen in our example.
Other popular options for executing JavaScript code in Magento 2 include applying the same configuration to multiple DOM elements.
Or when the JavaScript is not related to any DOM nodes, using an asterisk instead of a CSS selector.
Step five, add Magento module and test it. Finally, let’s add our Magento module and test the results.
Now we’ll go to any product page and we should see the “Hello World” message. -
Useful resources
recommendation-more-help
3a5f7e19-f383-4af8-8983-d01154c1402f