Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify basedir option (RequireJS-like)

I cannot figure out how the browserify basedir option works..

Note: I may be wrong in my understanding of the whole basedir concept because I'm coming from RequireJS (think baseUrl).

EDIT Indeed I was wrong, but you can still achieve what I was trying to do with the paths option, see my answer below.

I understand that the basedir option gives you the ability (the freedom!) to specify all require paths (starting with a .) from a static root/base dir.. And NOT from process.cwd()..

This is literally driving me crazy, I though such a feature would be so basic to implement and that a lot of people would have run into the same issue as me, but there is actually very few info on the web about how to setup properly the basedir option.. And trust me, this is not straight-forward..

So here is the BASIC example that's driving me crazy.

Given the following file structure:

js/
js/app.js
js/src/models/Person.js
js/src/views/PersonView.js

And running:

var browserify = require('browserify');
var gulp = require('gulp');

gulp.task('scripts', function() {

  var b = browserify('./app', {basedir: './js'});

  b.bundle().pipe(gulp.dest('./dist'));
});

I would expect being able to do the following require() call in PersonView.js:

var Person = require('./src/models/Person');
...

Instead of (which is obviously working...):

var Person = require('../models/Person');
...

But I get the following error:

Error: module "./src/models/Person" not found from "/Users/...some path.../js/src/views/PersonView.js"

What am I missing about the basedir option?

like image 855
eightyfive Avatar asked Mar 16 '14 08:03

eightyfive


1 Answers

It turns out that basedir is not the same as RequireJS's baseUrl. As stated by @Ben in the comment above, the official docs says:

opts.basedir is the directory that browserify starts bundling from for filenames that start with ..

(source)

Meaning that basedir only applies to the entry files. Further require calls deep in the file tree structure will always be resolved relatively to the file currently being parsed.

Answer to my question

The paths option of browser-resolve (which is used by browserify under the hood) is what I was looking for:

paths - require.paths array to use if nothing is found on the normal node_modules recursive walk

(source)

Just pass this option along with other browserify options when instantiating the bundler.

Note: It looks like it is messing up things when using together with browserify-shim transform.

like image 134
eightyfive Avatar answered Sep 28 '22 11:09

eightyfive