How can I add custom js file and compile using requirejs file in magento 2 ?
please give me details for this process.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityKeep your js file inside app/design/frontend/Vendor/themename/Vendor_Modulename/web/js/custom.js
You can add js using xml file with default.xml file,
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<link src="Vendor_Modulename::js/custom.js"/>
</head>
<body>
</body>
</page>
Run command to get js at compile time, php bin/magento setup:static-content:deploy
You can call js inside phtml file by calling,
<script>
require(["jquery"],function($){
// your js code
})
</script>
Second way,
create requirejs-config.js file, inside app/design/frontend/Vendor/themename/Vendor_Modulename/requirejs-config.js file
add js file inside, app/design/frontend/Vendor/themename/Vendor_Modulename/web/js/customfile.js
file
var config = {
map: {
'*': {
customjs: 'Vendor_Modulename/js/customfile'
}
}
};
call inside template file,,
<script type="text/javascript">
require(['jquery','customjs'],function($){
$('selector').customjs({
});
});
</script>
requiredjs with file name (../view/frontend/requirejs-config.js)
var config = {
"map": {
"*": {
"<js_tag_name>": "<vendor>_<module_name>/js/<js_name>"
}
}
};
Add your js to ../view/frontend/web/js/.js
define([
"jquery",], function($){
return function (config, element) {
<your_js_code>
}});