JavaScript require () on the client side

Is it possible to use require() (or something similar) on the client side?

Example

 var myClass = require('./js/myclass.js'); 
+79
javascript
Mar 02 '11 at 13:59
source share
14 answers

To do this, you should refer to require.js or head.js.

+41
Mar 02 2018-11-11T00:
source share

I used browserify . It also allows me to integrate Node.js modules into my client-side code.

I wrote about this here: Add Node.js / style CommonJS require () for client-side JavaScript with a browser

+22
Aug 05 2018-11-11T00:
source share

If you want to have Node.js style require , you can use something like this:

 var require = (function () { var cache = {}; function loadScript(url) { var xhr = new XMLHttpRequest(), fnBody; xhr.open('get', url, false); xhr.send(); if (xhr.status === 200 && xhr.getResponseHeader('Content-Type') === 'application/x-javascript') { fnBody = 'var exports = {};\n' + xhr.responseText + '\nreturn exports;'; cache[url] = (new Function(fnBody)).call({}); } } function resolve(module) { //TODO resolve urls return module; } function require(module) { var url = resolve(module); if (!Object.prototype.hasOwnProperty.call(cache, url)) { loadScript(url); } return cache[url]; } require.cache = cache; require.resolve = resolve; return require; }()); 

Beware: this code works, but is incomplete (especially for resolving the URL) and does not implement all the functions of Node.js (I just put this together last night). YOU SHOULD NOT USE THIS CODE in real applications, but it gives you a starting point. I tested it with this simple module and it works:

 function hello() { console.log('Hello world!'); } exports.hello = hello; 
+13
Dec 16 2018-11-12T00:
source share

I asked myself the same questions. When I looked into it, I found the choice overwhelming.

Fortunately, I found this great table to help you choose the best bootloader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

+12
Aug 05 2018-11-11T00:
source share

Take a look at the requirejs project.

+9
Mar 02 2018-11-11T00:
source share

I found that in general it is recommended to pre-process the scripts at compile time and bundle them in one (or very few) packages with replacing require with some “easy laying” also at compile time.

I was looking for the following “new” tools that could do this

And the already mentioned browserify should also fit in well - http://esa-matti.suuronen.org/blog/2013/04/15/asynchronous-module-loading-with-browserify/

What are system systems?

+7
Apr 23 '14 at 5:57 on
source share

You can create elements in the DOM, which loads the elements.

Like this:

 var myScript = document.createElement('script'); // Create new script element myScript.type = 'text/javascript'; // Set appropriate type myScript.src = './js/myclass.js'; // Load javascript file 
+4
Mar 02 2018-11-11T00:
source share

Just use Browserify, a kind of compiler that processes your files before it goes into production and packs the file into packages.

Think that you have a main.js file that requires your project files, when you launch a browser in it, it simply processes everything and creates a package with all your files, allowing you to synchronously use require calls to the browser without HTTP requests and with very small overhead for performance and packet size, for example.

See the link for more information: http://browserify.org/

+3
Feb 01 '14 at 17:33
source share

Some answers are already there, but I would like to point you to YUI3 and load the module on demand. It works both on the server (node.js) and on the client. I have a demo website that uses the same JS code that runs on any client or server to create pages, but this is a different section.

YUI3: http://developer.yahoo.com/yui/3/

Video: http://developer.yahoo.com/yui/theater/

Example:

(precondition: YUI3 core functions loaded in 7k yui.js)

 YUI({ //configuration for the loader }).use('node','io','own-app-module1', function (Y) { //sandboxed application code //... //If you already have a "Y" instance you can use that instead //of creating a new (sandbox) Y: // Y.use('moduleX','moduleY', function (Y) { // }); //difference to YUI().use(): uses the existing "Y"-sandbox } 

This code loads the YUI3 modules "node" and "io", and the module "native-application-module1", and then the callback function is run. A new sandbox "Y" is created with all the features of YUI3 and own-app-module1. Nothing is displayed in the global namespace. The loading of modules (.js files) is done by the YUI3 loader. It also uses (optionally not to show here) the configuration to select the version of -debug or -min (ified) modules to load.

+2
Mar 02 2018-11-11T00:
source share

Here's a solution that takes a completely different approach: packs all the modules into a JSON object and requires modules by reading and executing the contents of the file without additional requests.

https://github.com/STRd6/require/blob/master/main.coffee.md

STRd6 / require depends on the presence of a JSON package at run time. The require function is created for this package. The package contains all the files that your application may require. Additional HTTP requests are not executed because the package binds all the dependencies. It is so close that you can get Node.js style on the client.

The package structure is as follows:

 entryPoint: "main" distribution: main: content: "alert(\"It worked!\")" ... dependencies: <name>: <a package> 

Unlike Node, a package does not know its external name. It depends on the pacakge, including addiction, to name it. This provides complete encapsulation.

Given everything that sets up a function here that loads a file from a package:

 loadModule = (pkg, path) -> unless (file = pkg.distribution[path]) throw "Could not find file at #{path} in #{pkg.name}" program = file.content dirname = path.split(fileSeparator)[0...-1].join(fileSeparator) module = path: dirname exports: {} context = require: generateRequireFn(pkg, module) global: global module: module exports: module.exports PACKAGE: pkg __filename: path __dirname: dirname args = Object.keys(context) values = args.map (name) -> context[name] Function(args..., program).apply(module, values) return module 

This external context provides some variable that the modules have access to.

The A require function is exposed to modules, so they may need other modules.

Additional properties such as a reference to a global object and some metadata are also exposed.

Finally, we execute the program inside the module and the given context.

This answer will be most useful to those who want to have a synchronous Node.js require statement style in the browser and are not interested in remote script loading solutions.

+1
Sep 30 '13 at 6:12
source share

I find that a component project provides a much more streamlined workflow than other solutions (including require.js), so I would advise checking out https://github.com/component/component . I know this is a bit late answer, but may be useful to someone.

+1
May 27 '14 at 18:36
source share

Here's an easy way to use requires and exports to your web client. This is a simple wrapper that creates the global variable "namespace", and you transfer your CommonJS-compatible code to the "define" function as follows:

 namespace.lookup('org.mydomain.mymodule').define(function (exports, require) { var extern = require('org.other.module'); exports.foo = function foo() { ... }; }); 

More docs here:

https://github.com/mckoss/namespace

0
Apr 7 '11 at 18:50
source share

The clientide-require library provides an asynchronous load() function that can be used to load any JS file or NPM module (which uses module.exports ), any .css file, any .json , any .html , any any other file as text.

e.g. npm install clientside-require --save

 <script src = '/node_modules/clientside-require/dist/bundle.js'></script> <script> load('color-name') // an npm module .then(color_name=>{ console.log(color_name.blue); // outputs [0, 0, 255] }) </script> 

The really interesting part of this project is that inside any load() ed script you can use the synchronous require() function just like in the node.js file!

eg,

 load('/path/to/functionality.js') 

and inside /path/to/functionality.js :

 var query_string = require("qs") // an npm module module.exports = function(name){ return qs.stringify({ name:name, time:new Date() } } 

This last part, which implements the synchronous require() method, allows you to use NPM packages created to run on the server.




This module was designed to maximize the implementation of require functionality in a browser. Disclaimer: I wrote this module.

0
May 28 '18 at 18:42
source share

Yes, it is very easy to use, but you need to load the javascript file in the browser with the script tag

 <script src="module.js"></script> 

and then the user in the js file for example

 var moduel = require('./module'); 

I am making an application using an electron and it works as expected.

-four
Nov 27 '16 at 17:30
source share



All Articles