Context
I cloned a basic node-browserify boilerplate project and got it up. I'm using coffee-script. Right now, I'm trying to add jadeify to the equation as follows:
bundle = browserify
entry: __dirname + "/app/init.coffee"
debug: true
mount: "/app.js"
bundle.use jadeify __dirname + '/views'
app.use bundle
This is before I even attempt to use jadeify anywhere.
Issue
Everything works, until I add bundle.use(jadeify(__dirname + '/views')) as a middleware to browserify. Then I get the following error message in browser's console:
Uncaught ReferenceError: __require is not defined
According to the browser's console, the source of this message is /app.js.
Question
Why does this script fail with an error as soon as I try to add the jadeify middleware for browserify?
Motivation
I figured that it'll be more convenient to reuse server-side jade templates on client-side, so I'm ditching underscore templates in favor of jade. While doing my research, I came across this solution to a related question that suggests the use of jadeify. It seems doable, but something seems to be failing.
One can bypass jadeify by using browjadify
Usage:
browjadify --entry=app.coffee >bundle.js
Source: browjadify
#!/usr/bin/env node
var jade = require('jade')
var browserify = require('browserify')
var fs = require('fs');
var argv = require("optimist").argv;
var b = browserify()
b.register('.jade', function(body) {
var options = {"client": true, "compileDebug": false};
body = "module.exports = " + jade.compile(body, options).toString() +";";
return body;
});
var jaderuntime = require('fs').readFileSync(__dirname+"/node_modules/jade/runtime.js", 'utf8');
b.prepend(jaderuntime); // Brings in var jade that jade.compile needs
b.addEntry(argv.entry); // gets browserify to do its thing
console.log(b.bundle()); // the bundled output
I've seen this today as well and managed to fix it.
The problem for me was that jadeify depends on browserify version at most 1.2.9 but the current version of browserify in the git repo is newer (much newer, something above 1.8 if i remember correctly). And being new myself to working with this setup I installed browserify first (with the newest version) and then jadeify installed it's own dependent browserify (with the supproted version) in it's own module space.
Then when I was running my app the browserify I was calling was the new version but the libs that jadeify was using were the old version and this created a conflict somewhere and thus the error you were seeing as well.
I ended up just reinstalling the latest supported version of browserify in my app space and that fixed it.
LATER EDIT:
Problem with the fix above was that browserify#1.2.9 does not have caching and made reloading the server very slow. But I managed to find browserijade which works with the latest version of browserify (1.9.4) an does exactly the same things as jadeify.
Hope it helps!
Related
I'm in the process of re-writing my electron app with ES6, using Laravel Mix to compile the app JS and SASS. Now the main process loads up the render process fine. Once that happens my app.js loads up and that's where I have my issues. So I do:
import { remote } from 'electron';
Which causes this error in console:
Uncaught Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
Now i've tried reinstalling electron, even though electron works when the main process fires up to begin with. The line refers to this in the compiled js:
/* WEBPACK VAR INJECTION */(function(__dirname) {var fs = __webpack_require__(8)
var path = __webpack_require__(9)
var pathFile = path.join(__dirname, 'path.txt')
if (fs.existsSync(pathFile)) {
module.exports = path.join(__dirname, fs.readFileSync(pathFile, 'utf-8'))
} else {
throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
}
I'm not really sure what's going on, any advice or information would be a great help!
Thanks
Edit: I've tried running it with --verbose:
/Library/Caches/com.apple.xbs/Sources/AppleGVA/AppleGVA-10.1.16/Sources/Slices/Driver/AVD_loader.cpp: failed to get a service for display 3
2017-06-13 16:10:42.383 Electron Helper[47106:766924] Couldn't set selectedTextBackgroundColor from default ()
Most probably source of problem is that path.txt doesn't exists.
path.txt is generated while installing electron from npm. If you are not seeing any error while installing electron that means, errors are getting suppressed.
Troubleshoot: Check if node_modules/electron/path.txt exist. If not, then you have got a problem.
Solution:
Note: If on Windows, use native CMD instead of Git Bash
Try to install electron manually after npm install by executing following script
cd node_modules/electron && node install.js
This may take up a while, since it is going to download electron's full package.
I have been trying to get the following module to work on a react/webpack application:
https://github.com/ripjar/material-datetime-picker
Whenever I import the module my server wont start and it crashes with the syntax error: Uncaught SyntaxError: Unexpected token import.
It seems that throughout the modules code it is using es6 to import/export but each one of those lines breaks the module when I try to install and export it into my own file.
I have tried looking through the source code for the module as well as the standalone version but cant get either to work - however - I know that the module works inside a standalone HTML file as their demo still works when I download it locally.
Could this have to do with incompatibility with webpack? I have been working with their code along with a senior developer and we cant seem to get the module to load at all.
Apparently you're trying to import es6 module while not using es6 compiler like Babel
If you intend to use it with CommonJS you should consider adding it using require:
var MaterialDateTimePicker = require('material-datetime-picker');
I believe you are using this module/js for front-end(browser). I will suggest using babelify in your build environment. You can check documentation in given links.
webpack-for-browserify-users
babeljs.io-installation
babel/babelify
Babel transformation--
var fs = require("fs"); var browserify = require("browserify");
var babelify = require("babelify");
browserify({ debug: true })
.transform(babelify)
.require("./script.js", { entry: true })
.bundle()
.on("error", function (err) {
console.log("Error: " + err.message);
}).pipe(fs.createWriteStream("bundle.js"));
I am using Browserify (http://browserify.org/) to load a module in JavaScript. I keep getting the following error:
I have no idea why this is happening. I have a "package.json" file in a directory called "wordnet-develop", which is located in the same location as the JavaScript file.
Originally I thought that there might be a path problem. However, I did the same exact thing but with a test.js file, and it worked. So, I think that there may be something wrong with using package.json.
The beginning of the package.json file:
The beginning of my JavaScript file:
The directory containing the javascript file:
The directory (seen above as "wordnet-develop")containing the package.json file:
UPDATE
I replaced var WordNet = require('./wordnet-develop/node-wordnet'); with var WordNet = require('./wordnet-develop/lib/wordnet'); as suggested by klugjo.
It may have worked, but now I am getting a new error message:
This happened again but with 'async' module missing. I checked lib/wordnet, and it included requirements for bluebird and async, so that's probably the error source.
However, I now have no idea what to do. I'm new to node.js and modules, so I'm unfamiliar with solutions. Am I supposed to parse all of the code and find all the required modules online? Shouldn't they have been included in the module? Is the problem that I'm trying to use a node.js module in vanilla JavaScript?
I don't think what you are trying to do is supported: you have to link directly to the entry javascript file of the node-wordnet library.
Replace
var WordNet = require('./wordnet-develop/node-wordnet');
With
var WordNet = require('./wordnet-develop/lib/wordnet');
I have created a node.js application. I need to compile or do a check whether syntax error occurs before running the node.js service.I need to integrate this in jenkins. Kindly guide me to validate the node.js application
Look into TypeScript. It is a language which allows you to get autocomplete with types and fails compilation if you have some syntax errors. It is a superset of JavaScript and transpiles to JavaScript.
Node.js provides CLI option --check or -c for checking a given file for syntax errors without running it. When working with Linux or MacOS a command like the following one helps with checking all obvious javascript files in a folder for containing basically working code:
find -name "*.js" | xargs node -c
using eslint package https://www.npmjs.com/package/eslint
It's a very common library to check the syntax of any JS/TS framework
You can use 'node-syntax-error' module.
it helps you to detect and report syntax errors in source code strings.
When you type node src.js you get a friendly error report about exactly where the syntax error is. This module lets you check for syntax errors and report them in a similarly friendly format that wrapping a try/catch around Function() or vm.runInNewContext() doesn't get you.
For example:
var fs = require('fs');
var check = require('syntax-error');
var file = __dirname + '/src.js';
var src = fs.readFileSync(file);
var err = check(src, file);
if (err) {
console.error('ERROR DETECTED' + Array(62).join('!'));
console.error(err);
console.error(Array(76).join('-'));
}
Using
node --check
Only finds very grave errors and can be tricky to execute.
I would suggest to use a linter like 'eslint'. Because:
It integrates easily with (npm lint or yarn lint)
It catches almost all possible errors (way more than node -check)
I'm creating a file that requires huge libraries such as jquery and three.js using browserify. The compiling process takes several seconds, probably because it's recompiling all the libs for each minor change I make. Is there a way to speed it up?
Have you tried using the --insert-globals, --ig, or --fast flags? (they're all the same thing)
The reason it's slow may be that it's scanning all of jquery and d3 for __dirname, __filename, process, and global references.
EDIT:
I just remembered: Browserify will take any pre-existing require functions and fall back to using that. more info here
This means you could build a bundle for your static libs, and then only rebuild the bundle for your app code on change.
This coupled with my pre-edit answer should make it a lot faster.
There are a few options that can help:
--noparse=FILE is a must for things like jQuery and three.js that are huge but don't use require at all.
--detect-globals Set to false if your module doesn't use any node.js globals. Directs browserify not to parse a file looking for process, global, __filename, and __dirname.
--insert-globals Set to true if your module does use node.js globals. This will define those globals without parsing the module and checking to see if they're used.
I was able to speed up my build by externalizing ThreeJS, using noparse with it, and setting it not to create a source map for it.
Use https://github.com/substack/watchify while developing.
If you use grunt, you can use my grunt task : https://github.com/amiorin/grunt-watchify
It caches the dependencies and watches the filesystem. Because of this the build is very fast. You can use it with grunt-contrib-watch and grunt-contrib-connect or alone. You can find a Gruntfile.js example in the github repository.
If you don't use grunt, you can use the original watchify from #substack : https://github.com/substack/watchify
Using watchify is practically a must, as it actually caches your deps between reloads.
My builds dropped from 3-8s to under 1s. (The >3s builds were still using ignoreGlobals, detectGlobals=false, and even noParseing jQuery).
Here's how I use it with gulp and coffeescript:
gutil = require("gulp-util")
source = require("vinyl-source-stream")
watchify = require("watchify")
browserify = require("browserify")
coffeeify = require("coffeeify")
gulp.task "watchify", ->
args = watchify.args
args.extensions = ['.coffee']
bundler = watchify(browserify("./coffee/app.coffee", args), args)
bundler.transform(coffeeify)
rebundle = ->
gutil.log gutil.colors.green 'rebundling...'
bundler.bundle()
# log errors if they happen
.on "error", gutil.log.bind(gutil, "Browserify Error")
# I'm not really sure what this line is all about?
.pipe source("app.js")
.pipe gulp.dest("js")
.pipe livereload()
gutil.log gutil.colors.green 'rebundled.'
bundler.on "update", rebundle
rebundle()
gulp.task "default", ["watchify", "serve"]
EDIT: here's a JS translation:
var gutil = require("gulp-util")
var source = require("vinyl-source-stream")
var watchify = require("watchify")
var browserify = require("browserify")
var coffeeify = require("coffeeify")
gulp.task("watchify", function() {
var args = watchify.args
args.extensions = ['.coffee']
var bundler = watchify(browserify("./coffee/app.coffee", args), args)
bundler.transform(coffeeify)
function rebundle() {
gutil.log(gutil.colors.green('rebundling...'))
bundler.bundle()
// log errors if they happen
.on("error", gutil.log.bind(gutil, "Browserify Error"))
// I'm not really sure what this line is all about?
.pipe(source("app.js"))
.pipe(gulp.dest("js"))
.pipe(livereload())
gutil.log(gutil.colors.green('rebundled.'))
}
bundler.on("update", rebundle)
rebundle()
})
gulp.task("default", ["watchify", "serve"])
Update
You can also give it a try to persistify which can be used as a drop in replacement for watchify from the command line and from code.
Original answer below
=======
I'm currently using bundly: https://www.npmjs.com/package/bundly
FULL DISCLOUSURE: I wrote it
But the main difference of this wrapper is that it provides incremental building. It persists the browserify cache between runs and only parse the files that have changed without the need for the watch mode.
Currently the module does a bit more than only adding the cache, but I'm thinking that the logic that handles the incremental build part could be moved to a plugin, that way it can be used with browserify directly.
Check a demo here: https://github.com/royriojas/bundly-usage-demo
I wrote this to solve the problem of slow builds with browserify and commonjs-everywhere. If you run it in "watch" mode then it will automatically watch your input files and incrementally rebuild just any files that changed. Basically instantaneous and will never get slower as your project grows.
https://github.com/krisnye/browser-build