Node-Style Require for In-Browser JavaScript

Node-style require for in-browser javascript?

Check out ender. It does a lot of this.

Also, browserify is pretty good. I've used require-kiss¹ and it works. There are probably others.

I'm not sure about RequireJS. It's just not the same as node's. You may run into problems with loading from other locations, but it might work. As long as there's a provide method or something that can be called.

TL;DR- I'd recommend browserify or require-kiss.


Update:

1: require-kiss is now dead, and the author has removed it. I've since been using RequireJS without problems. The author of require-kiss wrote pakmanager and pakman. Full disclosure, I work with the developer.

Personally I like RequireJS better. It is much easier to debug (you can have separate files in development, and a single deployed file in production) and is built on a solid "standard".

how to use require in browser? js / html

tiktok-livestream-chat-connector is described, by its website, as:

A Node.js module to receive and decode livestream events like comments and gifts in realtime from TikTok LIVE by connecting to TikTok's internal WebCast push service.

At no point in its documentation does it mention compatibility with web browsers.

Browserify (and similar tools) can bundle up CommonJS modules into a single file so that they can run in environments which don't support CommonJS modules (e.g. browsers). They can't polyfill all the Node.js features that browsers don't support (like the ability to make raw socket network connections).

If a module needs to run on Node.js then you can't just move it to the browser.

You could write a program for Node.js that runs as a web service and operates as a bridge to whatever the module does. The the browser could connect to your web service with WebSockets or Ajax requests. The project links to an example of one.

javascript require in browser

You should take a look at Webpack.
It only takes a webpack.config.js that is pretty simple and then you're good to go.

var webpack = require('webpack');  
module.exports = {
entry: [
'webpack/hot/only-dev-server',
"./src/index.js"
],

output: {
path: __dirname + '/build',
filename: "app.js"
},

devtool: 'sourcemap',

jshint: {
esnext: true
},

module: {

preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}],

loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel']
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
stage: 1
}
},
{
test: /\.less$/,
loader: 'style-loader!css-loader!less-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|woff)$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
}
]
},

plugins: [
new webpack.NoErrorsPlugin()
]
};

In this example webpack will get my index.js (called entrypoint) and resolve every require down its path. The output file will be app.js thrown at /build folder.

The loaders are a bonus so Webpack can do some other fancy stuff!

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

Use node module in browser

Here is the forked version of Refify you can use in node.js as well as browsers.

Forked Refify

You can simply download the index.js and include it in your AngularJS application. and use it.

see the below code, I have added the whole forked index.js file in snippet and example at the end.

(function(obj) {  if (typeof exports === 'undefined') {    obj.refify = refify;  } else {    module.exports = refify;  }

function refify(obj) { var objs = []; var paths = []
var keyStack = []; var objStack = [];
return walk(obj);
function walk(it) { if (typeof it !== 'object') { return it; } objs.push(it); paths.push(keyStack.slice()) objStack.push(it) var copy = initCopy(it); for (var k in it) { keyStack.push(k); var v = it[k]; var i = objs.indexOf(v); if (i == -1) { copy[k] = walk(v) } else { var $ref = '#/' + paths[i].join('/'); copy[k] = { $ref: $ref }; } keyStack.pop(); } objStack.pop(); return copy; } }
refify.parse = function(it) { if (typeof it !== 'object') it = JSON.parse(it);
var keyStack = []; var copy = initCopy(it);
walk(it);
return copy;
function walk(obj) { if (typeof obj !== 'object') { set(copy, keyStack.slice(), obj); return; } for (var k in obj) { keyStack.push(k); var current = obj[k]; var objPath = parseRef(current); while (objPath) { current = get(copy, objPath); objPath = parseRef(current); } if (current === obj[k]) { // We did *not* follow a reference set(copy, keyStack.slice(), initCopy(current)); walk(current); } else { // We *did* follow a reference set(copy, keyStack.slice(), current); } keyStack.pop(); } } }
refify.stringify = function(obj, replacer, spaces) { return JSON.stringify(refify(obj), replacer, spaces) }
function parseRef(value) { if (typeof value !== 'object') return false; if (!value.$ref) return false; var path = value.$ref == '#/' ? [] : value.$ref.split('/').slice(1); return path }
function get(obj, path) { if (!path.length) return obj; if (typeof obj !== 'object') return; var next = obj[path.shift()]; return get(next, path); }
refify.set = set;
function set(obj, path, value) { if (path.length === 0) throw new Error("Cannot replace root object"); var key = path.shift(); if (!path.length) { obj[key] = value; return; } switch (typeof obj[key]) { case 'undefined': obj[key] = isNaN(parseInt(key, 10)) ? {} : []; break; case 'object': break; default: throw new Error("Tried to set property " + key + " of non-object " + obj[key]); } set(obj[key], path, value); }
function initCopy(obj) { if (typeof obj !== 'object') return obj; return Array.isArray(obj) ? [] : {} }
}(this));

// Example with forked version
var obj = { inside: { name: 'Stackoverflow', id: '98776' }};
obj.inside.parent = obj;
var refifyObject= refify(obj);
document.getElementById("out").innerHTML = JSON.stringify(refifyObject);
<div id="out"></div>

What is this JavaScript require?

So what is this "require?"

require() is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.

Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include, Python's import, and so on.

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.

  • In browser JavaScript, scripts are added via the <script> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.

  • In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports or module.exports. For a module to access another module's exports or module.exports, it must use require().

In your code, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable.

Why does it work in node but not in a webpage?

require(), module.exports and exports are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.

Also, before I got it to work in node, I had to do npm install pg. What's that about?

NPM is a package repository service that hosts published JavaScript modules. npm install is a command that lets you download packages from their repository.

Where did it put it, and how does Javascript find it?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory.

How do I define require while running code in browser?

For any beginners like me who are trying to do this... just run JS and reference it from your HTML script. This(from my understanding) does not work! Node JS will not be compatible!



Related Topics



Leave a reply



Submit