Magento2 – How to Add External JS Globally

javascriptmagento2requirejs

I'm trying to add external js in my module which will be applicable on all pages on frontend. This is the process I've followed:
1. Code in my layout file app/code/Lapisbard/General/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="frontend-1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Lapisbard_General::js/ro_allpage.js"/>
    </head>
    <body/>
</page>

2. Added js file at app/code/Lapisbard/General/view/frontend/web/js/ro_allpage.js with following code

define('js/theme', [
    'jquery',
    'domReady!'
], function ($) {
    'use strict';
    console.log('Hello');
});

I see my file is being added on the page but it throws console error Uncaught ReferenceError: define is not defined. What I'm doing wrong?
Also I tried code below which throws Uncaught ReferenceError: require is not defined

require(["jquery"], function($){
    console.log("hello");
});

Best Answer

Place requirejs-config.js in the view/frontend folder of your module. Requirejs-config.js looks like:

 var config = {
map: {
    '*': {
        mycustomjs:           'Vendor_Module/js/mycustomjs',

    }
}};

and now Then in your phtml file

  require(['jquery', 'mycustomjs'], function($,mycustomjs){
      $(function(){
         // Custom code here
    });
 });