Search code examples
javascriptcoffeescriptgulpbrowserifycommonjs

Fixing Module Not Found with Browserify for Local Relative Requires


I have a demo NPM framework structured as the following:

./src/child.coffee

module.exports = class Child

./src/parent.coffee

Child = require "./child"
module.exports = class Parent

./gulp.js

require('coffee-script/register');
require('./gulpfile.coffee');

./gulp.coffee

gulp = require "gulp"

util = require "gulp-util"
coffee = require "gulp-coffee"
browserify = require "gulp-browserify"

gulp.task "build", ->
  gulp.src("./src/**/*.coffee")
    .pipe(coffee().on("error", util.log))
    .pipe(gulp.dest("./lib/"))

Everything works great if I run gulp build. However, I'm trying to introduce Browserify by adding the following to the build task:

gulp.task "build", ->
  gulp.src("./src/**/*.coffee")
    .pipe(coffee().on("error", util.log))
    .pipe(browserify())
    .pipe(gulp.dest("./lib/"))

With that in place the relative requires within the framework fail:

events.js:85 throw er; // Unhandled 'error' event ^ Error: module "./child" not found from "/Users/kevin/Desktop/demo/src/fake_d1543b04.js" at notFound (/Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/index.js:803:15) at /Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/index.js:754:23 at /Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/node_modules/browser-resolve/index.js:185:24 at /Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/node_modules/resolve/lib/async.js:36:22 at load (/Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/node_modules/resolve/lib/async.js:54:43) at /Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/node_modules/resolve/lib/async.js:60:22 at /Users/kevin/Desktop/demo/node_modules/gulp-browserify/node_modules/browserify/node_modules/resolve/lib/async.js:16:47 at FSReqWrap.oncomplete (fs.js:95:15)

How does one properly setup relative requires within a framework and have it work with gulp and coffeescript? Changing the require to be for a dependency from the package.json (i.e. Lodash = require "lodash") allows gulp to build. Furthermore changing from coffeescript to regular javascript also fixes the problem.


Solution

  • The problem is likely the .coffee extension. You need to instruct browserify to look for that extension. See opts.extensions. I don't know how you'd do that with gulp-browserify, but you're better off not using it anyway (it's blacklisted by gulp, if that matters to you, and I believe it's unmaintained).