I am trying browserify for first time with my express app. I have installed browserify globally. I am getting the error mentioned in subject. I have looked this over several times and all looks correct. I'm thinking maybe something w/browserify and express. My setup is
app.use(express.static(path.join(__dirname, 'public')));
I used this command to install browserify
browserify public/javascripts/main.js -o public/javascripts/bundle.js
My directory structure is
root
---public
---javascripts
bundle.js
main.js
and my ejs
<script src="javascripts/bundle.js"></script>
<script src="javascripts/main.js"></script>
which are 200 ok.
And my main.js contains line
let helper_functions = require('./library/helper_functions');
Is there something I've missed. All docs point to this is how you do it. Any guidance much appreciated.
Update: I just want clarify if Im exported several functions in helper_function.js it can be done like:
let helper_functions =
function strToNumberArray(str, separator = ',') {
// function stuff
}
// Function to convert string to an array then convert each element to a number
// ========================================================================================== //
function strToNumberArray(str, separator = ',') {
function stuff//
}
module.export = helperFunctions;
Related
I use the FayeJS and the latest version has been modified to use RequireJS, so there is no longer a single file to link into the browser. Instead the structure is as follows:
/adapters
/engines
/mixins
/protocol
/transport
/util
faye_browser.js
I am using the following nodejs build script to try and end up with all the above minified into a single file:
var fs = require('fs-extra'),
requirejs = require('requirejs');
var config = {
baseUrl: 'htdocs/js/dev/faye/'
,name: 'faye_browser'
, out: 'htdocs/js/dev/faye/dist/faye.min.js'
, paths: {
dist: "empty:"
}
,findNestedDependencies: true
};
requirejs.optimize(config, function (buildResponse) {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use config.out to get the optimized file contents.
var contents = fs.readFileSync(config.out, 'utf8');
}, function (err) {
//optimization err callback
console.log(err);
});
The content of faye_browser.js is:
'use strict';
var constants = require('./util/constants'),
Logging = require('./mixins/logging');
var Faye = {
VERSION: constants.VERSION,
Client: require('./protocol/client'),
Scheduler: require('./protocol/scheduler')
};
Logging.wrapper = Faye;
module.exports = Faye;
As I under stand it the optimizer should pull in the required files, and then if those files have required files, it should pull in those etc..., and and output a single minified faye.min.js that contains the whole lot, refactored so no additional serverside calls are necessary.
What happens is faye.min.js gets created, but it only contains the content of faye_browser.js, none of the other required files are included.
I have searched all over the web, and looked at a heap of different examples and none of them work for me.
What am I doing wrong here?
For anyone else trying to do this, I mist that on the download page it says:
The Node.js version is available through npm. This package contains a
copy of the browser client, which is served up by the Faye server when
running.
So to get it you have to pull down the code via NPM and then go into the NPM install dir and it is in the "client" dir...
I have a nodeJS server with many modules and nested modules I want to startup while console.logging a message so I made something like this.
global.REQUIRE = function(path) {
console.log('loading module ' + path);
return require(path);
};
And instead of having require('./constants/app-constants.js') I would have global.REQUIRE('./constants/app-constants.js');.
But path isn't properly resolved because I have some nested modules and REQUIRE method is in application-main.js on root folder so require solves from there apparently. I don't think it's wrong I just comment my first attemp.
My second attempt was then using require('path').resolve and do something like this.
var resolve = require('path').resolve;
global.REQUIRE(resolve('./constants/app-constants.js'));
But this doesn't properly resolve either. Console outputs something like
/home/$USER/git/nodeJS/constants/app-constants.js
instead of what should output
/home/$USER/git/nodeJS/app/constants/app-constants.js
index.js with the requires is inside app/ folder and old require('./constants/app-constants.js') works fine from there.
I am new to Browserify and trying the following:
I created a node server and trying to get a package called 'openbci' running on the browser.
so I have the following file structure:
Myapp
-...
-public
--app.js
--index.html
--openBCI.js
--...
--javascript
---openBCI
----bundle.js
---...
-node_modules
--openbci
---openBCIBoard.js
--browserify
--...
my app.js file sets the server to serve the public folder
// app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.listen(myPort);
then I created the following openBCI.js
// openBCI.js
var OpenBCIBoard = require('openbci').OpenBCIBoard;
exports.OpenBCIBoard = OpenBCIBoard;
and finally launched the browserify command:
$ browserify public/openBCI.js > public/javascript/openBCI/bundle.js
but once called in my index.html file, I got an Uncaught TypeError: exists is not a function at Function.getRoot:
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
**if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {**
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}
It appears that it could not find the original path for the module.
Could you please tell me what is to change? Or if I understood at all how browserify works ? :)
I notice a few things that seem strange about the code.
exists is undefined in JavaScript or node. It appears to be an alias of fs.exists - is that right?
If so, fs.exists is deprecated. Per the documentation, you can achieve the same effect with fs.stat or fs.access. Note however that you should either supply a callback (preferable) or use the Sync version of these methods.
If you are trying to use file system tools in the browser you are going to run into problems because you are attempting to access the server's file system from the browser. There is a plugin, browserify-fs, that gives you an equivalent to fs in the browser. However, this seems to access the browser's local IndexedDB, not the storage on your server.
I would suggest running code that relies on server-side files on the server, rather than in the browser.
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
But now I get the following error when running my test:
ReferenceError: expect is not defined
This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
"Error: Cannot find module './does-not-exist.js'"
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
Create test/helper.js:
var expect = require("expect.js")
global.expect = expect;
and set your test/mocha.opts to:
--require test/helper
While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:
Install:
npm install karma-chai --save-dev
Configure:
karma.set({
frameworks: ['mocha', 'chai']
// ...
});
Use:
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.
My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.
I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.
I found that exporting is easy:
class Foo{...}
class Bar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };
or
class Buzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;
However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:
if (typeof require !== 'undefined') {
var {Foo,Bar} = require('./foobar.js');
}
So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:
--require test/mocha.opts.js
mocha.opts.js content. The paths are relative to the location of the file:
global.assert = require('assert');
global.Foo = require("../foobar.js").Foo;
global.Bar = require("../foobar.js").Bar;
global.Buzz = require("../buzz.js");
I am a beginner to node js and angular js.
I have a string which is html text and i want to convert it to jade.
I can do this with node js module 'html2jade' but when I am writing my code in js file (in controller), it is giving me a 'require' is not defined error.
This is the code:
app.controller('comicController', function($scope, resources) {
$scope.searchComic = function() {
resources.routes.charactersAPI.fetch({title: $scope.title}, function done(response) {
console.log(response);
$scope.comic = response;
//$scope.comic.description
require('html2jade').convertHtml($scope.comic.description, {}, function (err, jade) {
$scope.desc = jade;
});
});
};
});
Any help is appreciated. Thanks in advance!
You require a module on your build process.
Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.
Install browserify
npm install -g browserify
Write a module
// hello.js
module.exports = function(name) {
return 'Hello ' + name + '!';
}
Use the module
// app.js
var greetings = require('./hello');
alert(greetings('Christophe'));
Create the bundle
browserify app.js -o bundle.js
Refer your bundle
<html>
<body>
<script src="bundle.js"></script>
</body>
</html>
Browserify is a tool that lets you bundle node.js modules and consume them in the browser. In other words, it allows you to write browser-based applications using node.js-style requires.
You can check here for reference.