2

I add JS file in custom module

Vendor\Module\view/adminhtml/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <head>
     <css src="Vendor_Module::css/test.css"/>
     <script src="Vendor_Module::js/test.js"/>
   </head>
</page>

Add js file in web folder as below path:

view/adminhtml/web/js/test.js

code for checking .

require([ 'jquery', 'jquery/ui'], function($){
    $(document).ready(function($) {
        console.log('asdf');
    });
});

File include in admin panel But error is TypeError: require is not a function how can see message in console ?

  • 1
    don't you mean define instead of require? also is this the javascript code that is in you JS-file or is this somewhere else? – Philipp Sander Mar 20 at 14:39
  • use also define but same error TypeError: define is not a defined – HaFiz Umer Mar 20 at 16:21
  • "define is not a defined" is not a message javascript would EVER print. please make sure that you provide us the correct error – Philipp Sander Mar 20 at 16:28
  • It seems like you are overwriting the default.xml in module backend and therefore require.js is not loaded anymore – HelgeB Mar 20 at 18:02
  • Refer this answer may be it will solve your problem – ABHISHEK TRIPATHI Mar 21 at 9:19
0

Here is how to add js in module, the best way is to add it via require-js

  1. app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            prince: 'Vendor_module/js/prince',
        }
    }
};
  1. app/code/Vendor/Module/view/frontend/web/js/prince.js
define(['jquery'], function($){
   "use strict";
       alert("Yesss, it works !");
});
  1. app/code/Vendor/Module/view/frontend/templates/file.phtml
<script type="text/javascript">
    require(['jquery', 'prince'], function($, prince) {
    });
</script>

Don't forget to :

  • clean the cache

  • clean var/view_preprocessed content

  • clean pub/static content

  • deploy the static content : php bin/magento setup:static-content:deploy -f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.