Home > Enterprise >  Is there something like Jquery Require function in vanilla JS
Is there something like Jquery Require function in vanilla JS

Time:05-21

I have use requirJS require function, but I want something like this in vanilla javaScript. How do I resolve this?

require(['underscore', 'jquery', 'settings', 'text!/core/users/settings.js/?v='   ( new Date)], function (_, $, Settings, userSettings) {

    userSettings = (typeof userSettings === "object" || typeof userSettings === 'function') && (userSettings !== null) ? userSettings : JSON.parse(userSettings)
    console.log('settings', Settings);
    

}); 

CodePudding user response:

The function require (at least the one you are using) is part of Require.js and has nothing to do with jQuery. It implements AMD modules.

Browsers have no native support for AMD modules.

Modern browsers do have native support for ECMAScript modules.

Use <script type="module"> to load the module that acts as your entry point.

You can then use import (e.g. import defaultExport from 'url/to/module.js') to import values exported (e.g. export default someVariable;) from that module.

MDN has further information on the subject.

CodePudding user response:

Simply put, you’d want to use <script> tags to use the other libraries.

Alternatively, you may be able to use the async “import()” syntax.

Even more alternatively, you could be super jank about it and send a request to fetch the library from some CDN or NPM’s tarball (though the NPM solution probably won’t work due to having to decompress the .tar file), then set some variable equal to the received fetch data, essentially emulating what the <script> tag will do for you, but in plain JS.

  • Related