I am learning about how to create/import/export modules in Node.js,
i have gone through these and was trying to learn by creating a sample application.
I issued the command from the root folder (Poc1) "npm install requirejs", and included the file require.js in the Start.html.
When i open Start.html in browser i get -
"Uncaught ReferenceError: require is not defined", "Uncaught ReferenceError: module is not defined".
I am not sure what mistake i am making or what other files i need to include to get it working ?
For sample application below is folder structure
Poc1 folder has these files and folders (greetings.js, main.js, Start.html, node_modules)
Poc1\node_modules has (requirejs\require.js)
grreetings.js is defined as below
module.exports.sayHelloInEnglish = function(){
return "Hello";
}
module.exports.sayHelloInSpanish = function(){
return "Hola";
}
main.js is defined as below
var greetings = require("./greetings.js");
function someFunc(){
var g1 = greetings.sayHelloInEnglish();
var g2 = greetings.sayHelloInSpanish();
alert(g1);
alert(g2);
}
Start.html is defined as below
<html>
<head>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript" src="greetings.js"></script>
<script type="text/javascript" src="node_modules\requirejs\require.js"></script>
</head>
<body>
<span>Below is button</span>
<input type="button" onclick="someFunc()" value="clickMe"/>
</body>
</html>
Ok, I think those exports aren't correct:
exports.sayHelloInEnglish = function(){
return "Hello";
}
exports.sayHelloInSpanish = function(){
return "Hola";
}
I am trying to write a simple Hello world app in react.js using component based approach. So I am using requie.js. I have 4 files in the same folder namely index.html, index.js,world.js and require.js. I am having a script tag in index.html which will load index.js. But I am loading the world.js via require.js using module.exports, which would result in error. Here is my code
index.html
<head>
<script src="https://fb.me/react-0.13.3.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script data-main="index.js" src="require.js"></script>
</script>
</head>
<body>
<script type="text/jsx" src="index.js"></script>
</body>
index.js
var world = require('./world');
var Hello = React.createClass({
render:function(){
return (<div>
<div>Hello,</div>
<world/>
</div>)
}
})
var element = React.createElement(Hello);
React.render(element,document.body);
world.js
module.exports = React.createClass({
render: function(){
return (<div>World!</div)
}
})
I am intending to show Hello, World. But I'm getting the following errors
Uncaught SyntaxError: Unexpected token <
fbcdn-dragon-a.akamaihd.net/hphotos-ak-xtf1/t39.3284-6/11057100_835863049837306_1087123501_n.js:314 You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx
require.js:8 Uncaught Error: Module name "world" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
:8000/index.js:5 Uncaught SyntaxError: Unexpected token <
First of all, the component "world" should start with an upper case. I went ahead and put the code in a single file so that you can see it a little more clear:
<!DOCTYPE html>
<html>
<head>
<title>Hello React!</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/jsx">
var World = React.createClass({
render: function(){
return (
<div>World!</div>
);
}
});
var Hello = React.createClass({
render:function(){
return (
<div>
<div>Hello,
<World />
</div>
</div>
);
}
});
React.render(<Hello />,document.getElementById('example'));
</script>
</body>
</html>
What I would recommend is that you setup a proper environment for development with node and npm installed. I have a project in github that is a skeleton that you can use to get up and running without having to worry about how it works for now: reactjs skeleton.
I hope this helps!
There are at least three issues here. First, you are not using the correct require syntax for asynchronous loading. Your index.js should be:
define(['world'], function(world) {
var Hello = React.createClass({
render:function(){
return (<div>
<div>Hello,</div>
<world/>
</div>)
}
})
var element = React.createElement(Hello);
React.render(element,document.body);
});
Second, since index.js and world.js are jsx files, requirejs needs a plugin that will tell it that. Something like:
https://github.com/philix/jsx-requirejs-plugin
Finally, since you are loading index.js via requirejs, you don't need:
<script type="text/jsx" src="index.js"></script>
Any time I try to load socket.io 1.0.x after require.js, it produces
Uncaught ReferenceError: io is not defined
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script type="text/javascript">
var socket = io('http://localhost');
</script>
But if I put socket.io before require.js, it doesn't produce any error:
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script type="text/javascript">
var socket = io('http://localhost');
</script>
This of course means that socket.io cannot be loaded by require.js this way:
requirejs.config({
paths: {
'socketio' : ['https://cdn.socket.io/socket.io-1.0.6'],
},
shim: {
'socketio': {
exports: 'io'
}
}
});
require(['socketio'], function(io){
console.log(window.io); //undefined
})
Socket.io 0.x
with socket.io 0.x you needed in to export io in the require.js config:
shim: {
'socket.io-client': {
exports: 'io'
}
}
and your js file:
define(['socket.io-client'], function () {
// io is exported here
var socket = io.connect ...
}
Socket.io 1.x
with socket.io 1.x, no need to export io in the require.js config file
and your js file:
define(['socket.io-client'], function (io) {
// io an argument of the function
var socket = io.connect ...
}
But in both cases, you have to use the io object in the define so that it is loaded correctly by require.js when you need it.
Also note that you need socket.io-client instead of socket.io in the browser
RequireJS creates a require and define set of methods... the socket.io js file sees this, and defines itself.
Include socket.io first or Use AMD
I specifically wanted the bower packages (ng-socket), and socket.io-client to cooperate via RequireJS. At first ng-socket errored because io was undefined, even with shimmed deps.
So, I added a startSocketIo.js file:
define([
'socket.io-client'],function(io) {
window.io = io;
});
and added a deps section to the root of my require config file:
deps: [
'./startSocketIo'
],
I see this as analogous to adding via a script tag and no better for performance, but it allowed me to keep using unmodified bower packages and using requirejs for all my js.
I am new to nodejs and browserify. I started with this link .
I have file main.js which contains this code
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
this.LogData =function(){
console.log(unique(data));
};
Now I Install the uniq module with npm:
npm install uniq
Then I bundle up all the required modules starting at main.js into a single file called bundle.js with the browserify command:
browserify main.js -o bundle.js
The generated file looks like this:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
this.LogData =function(){
console.log(unique(data));
};
},{"uniq":2}],2:[function(require,module,exports){
"use strict"
function unique_pred(list, compare) {
var ptr = 1
, len = list.length
, a=list[0], b=list[0]
for(var i=1; i<len; ++i) {
b = a
a = list[i]
if(compare(a, b)) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique_eq(list) {
var ptr = 1
, len = list.length
, a=list[0], b = list[0]
for(var i=1; i<len; ++i, b=a) {
b = a
a = list[i]
if(a !== b) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique(list, compare, sorted) {
if(list.length === 0) {
return []
}
if(compare) {
if(!sorted) {
list.sort(compare)
}
return unique_pred(list, compare)
}
if(!sorted) {
list.sort()
}
return unique_eq(list)
}
module.exports = unique
},{}]},{},[1])
After including bundle.js file into my index.htm page, how do I call logData function ??
The key part of bundling standalone modules with Browserify is the --s option. It exposes whatever you export from your module using node's module.exports as a global variable. The file can then be included in a <script> tag.
You only need to do this if for some reason you need that global variable to be exposed. In my case the client needed a standalone module that could be included in web pages without them needing to worry about this Browserify business.
Here's an example where we use the --s option with an argument of module:
browserify index.js --s module > dist/module.js
This will expose our module as a global variable named module.
Source.
Update:
Thanks to #fotinakis. Make sure you're passing --standalone your-module-name. If you forget that --standalone takes an argument, Browserify might silently generate an empty module since it couldn't find it.
Hope this saves you some time.
By default, browserify doesn't let you access the modules from outside of the browserified code – if you want to call code in a browserified module, you're supposed to browserify your code together with the module. See http://browserify.org/ for examples of that.
Of course, you could also explicitly make your method accessible from outside like this:
window.LogData =function(){
console.log(unique(data));
};
Then you could call LogData() from anywhere else on the page.
#Matas Vaitkevicius's answer with Browserify's standalone option is correct (#thejh's answer using the window global variable also works, but as others have noted, it pollutes the global namespace so it's not ideal). I wanted to add a little more detail on how to use the standalone option.
In the source script that you want to bundle, make sure to expose the functions you want to call via module.exports. In the client script, you can call these exposed functions via <bundle-name>.<func-name>. Here's an example:
My source file src/script.js will have this:
module.exports = {myFunc: func};
My browserify command will look something like this:
browserify src/script.js --standalone myBundle > dist/bundle.js
And my client script dist/client.js will load the bundled script
<script src="bundle.js"></script>
and then call the exposed function like this:
<script>myBundle.myFunc();</script>
There's no need to require the bundle name in the client script before calling the exposed functions, e.g. <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> isn't necessary and won't work.
In fact, just like all functions bundled by browserify without standalone mode, the require function won't be available outside of the bundled script. Browserify allows you to use some Node functions client-side, but only in the bundled script itself; it's not meant to create a standalone module you can import and use anywhere client-side, which is why we have to go to all this extra trouble just to call a single function outside of its bundled context.
I just read through the answers and seems like nobody mentioned the use of the global variable scope? Which is usefull if you want to use the same code in node.js and in the browser.
class Test
{
constructor()
{
}
}
global.TestClass = Test;
Then you can access the TestClass anywhere.
<script src="bundle.js"></script>
<script>
var test = new TestClass(); // Enjoy!
</script>
Note: The TestClass then becomes available everywhere. Which is the same as using the window variable.
Additionally you can create a decorator that exposes a class to the global scope. Which is really nice but makes it hard to track where a variable is defined.
Read README.md of browserify about --standalone parameter
or google "browserify umd"
Minimal runnable example
This is basically the same as: https://stackoverflow.com/a/43215928/895245 but with concrete files that will allow you to just run and easily reproduce it yourself.
This code is also available at: https://github.com/cirosantilli/browserify-hello-world
index.js
const uniq = require('uniq');
function myfunc() {
return uniq([1, 2, 2, 3]).join(' ');
}
exports.myfunc = myfunc;
index.html
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Browserify hello world</title>
</head>
<body>
<div id="container">
</body>
</div>
<script src="out.js"></script>
<script>
document.getElementById('container').innerHTML = browserify_hello_world.myfunc();
</script>
</html>
Node.js usage:
#!/usr/bin/env node
const browserify_hello_world = require('./index.js');
console.log(browserify_hello_world.myfunc());
Generate out.js for browser usage:
npx browserify --outfile out.js --standalone browserify_hello_world index.js
Both the browser and the command line show the expected output:
1 2 3
Tested with Browserify 16.5.0, Node.js v10.15.1, Chromium 78, Ubuntu 19.10.
To have your function available from both the HTML and from server-side node:
main.js:
var unique = require('uniq');
function myFunction() {
var data = [1, 2, 2, 4, 3];
return unique(data).toString();
}
console.log ( myFunction() );
// When browserified - we can't call myFunction() from the HTML, so we'll externalize myExtFunction()
// On the server-side "window" is undef. so we hide it.
if (typeof window !== 'undefined') {
window.myExtFunction = function() {
return myFunction();
}
}
main.html:
<html>
<head>
<script type='text/javascript' src="bundle.js"></script>
<head>
<body>
Result: <span id="demo"></span>
<script>document.getElementById("demo").innerHTML = myExtFunction();</script>
</body>
</html>
Run:
npm install uniq
browserify main.js > bundle.js
and you should get same results when opening main.html in a browser as when running
node main.js
Whole concept is about wrapping.
1.) Alternative - Object "this"
for this purpose I'll assume you have "only 1 script for whole app {{app_name}}" and "1 function {{function_name}}"
add function {{function_name}}
function {{function_name}}(param) { ... }
to object this
this.{{function_name}} = function(param) { ... }
then you have to name that object to be available - you will do it add param "standalone with name" like others advised
so if you use "watchify" with "browserify" use this
var b = browserify({
...
standalone: '{{app_name}}'
});
or command line
browserify index.js --standalone {{app_name}} > index-bundle.js
then you can call the function directly
{{app_name}}.{{function_name}}(param);
window.{{app_name}}.{{function_name}}(param);
2.) Alternative - Object "window"
add function {{function_name}}
function {{function_name}}(param) { ... }
to object window
window.{{function_name}} = function(param) { ... }
then you can call the function directly
{{function_name}}(param);
window.{{function_name}}(param);
You have a few options:
Let plugin browserify-bridge auto-export the modules to a generated entry module. This is helpful for SDK projects or situations where you don't have to manually keep up with what is exported.
Follow a pseudo-namespace pattern for roll-up exposure:
First, arrange your library like this, taking advantage of index look-ups on folders:
/src
--entry.js
--/helpers
--- index.js
--- someHelper.js
--/providers
--- index.js
--- someProvider.js
...
With this pattern, you define entry like this:
exports.Helpers = require('./helpers');
exports.Providers = require('./providers');
...
Notice the require automatically loads the index.js from each respective sub-folder
In your subfolders, you can just include a similar manifest of the available modules in that context:
exports.SomeHelper = require('./someHelper');
This pattern scales really well and allows for contextual (folder by folder) tracking of what to include in the rolled-up api.
You can also call your function from the html file like this:
main.js: (will be in bundle.js)
window.onload = function () {
document.getElementById('build-file')
.addEventListener('click', buildFile)
}
function buildFile() {
...
}
index.html:
<button id="build-file"">Build file</button>
window.LogData =function(data){
return unique(data);
};
Call the function simply by LogData(data)
This is just a slight modification to thejh's answer but important one
For debugging purposes I added this line to my code.js:
window.e = function(data) {eval(data);};
Then I could run anything even outside the bundle.
e("anything();");
I am trying to update the bust variable in require.js so the browser is forced to re-fetch instead of loading resources from cache. I found here that several people have asked similar question. I am trying to try with a simple piece of code.
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
<!-- This is a special version of jQuery with RequireJS built-in -->
<script>
var require = {
urlArgs : "bust="+getRandom()
};
</script>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
</head>
<body>
<h1 id="heading">jQuery+RequireJS Sample Page</h1>
<p>Look at source or inspect the DOM to see how it works.</p>
</body>
I am trying to get the value of my build number from a properties file on the server. But I get the following error:
Uncaught ReferenceError: getRandom is not defined
So I tried this:
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
var require = {
urlArgs : "bust="+getRandom()
};
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
But I get this error:
Uncaught TypeError: Property 'require' of object [object Object] is not a function
It looks like the bust variable has to be set even before require-jquery.js is declared but how do I access server side APIs without access to jquery libraries? I want to update the bust variable for every build.
Any pointers in the right directions would be really appreciated.
Thanks.