Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browserify based project dependencies issue #48

Closed
maratfakhreev opened this issue Feb 22, 2015 · 9 comments
Closed

Browserify based project dependencies issue #48

maratfakhreev opened this issue Feb 22, 2015 · 9 comments

Comments

@maratfakhreev
Copy link

I'm trying to replace CoffeeScript to ES6 in my project. It's Cordova based project which uses gulp + bower + browserify + marionette.js and some other libs. I ran into a problem, third-party libraries (for example Backbone) complain on 'use strict'. If I'm not mistaken It's because browserify compile project into one file and wraps each dependency with 'use strict' mode. How can I fix it? Here is my browserify config and apps start file. This configuration with coffeify works correct.

path = require('path')
gulp = require('gulp')
source = require('vinyl-source-stream')
buffer = require('vinyl-buffer')
browserify = require('browserify')
remapify = require('remapify')
watchify = require('watchify')
notify = require('gulp-notify')
cdv = require('cordova-lib').cordova.raw
config = require('../config')
root = process.cwd()
buildDir = path.join(root, config.buildDir)

babelify = require('babelify')

gulp.task 'browserify', ->
  bundler = browserify(
    cache: {}
    packageCache: {}
    fullPaths: true
    debug: config.isDevelopment()
    extensions: ['.jade']
    entries: "./#{config.appDir}/scripts/main.js"
  )
  .plugin(remapify, [
    src: '**/*.js'
    expose: 'scripts'
    cwd: "./#{config.appDir}/scripts"
  ])
  .plugin(remapify, [
    src: '**/*.jade'
    expose: 'templates'
    cwd: "./#{config.appDir}/templates"
  ])
  .transform('browserify-shim')
  .transform('jadeify')
  .transform(babelify.configure(
    extensions: ['.js']
    sourceMapRelative: "./#{config.appDir}"
  ))

  bundle = ->
    bundler.bundle()
      .on('error', notify.onError())
      .pipe(source('application.js'))
      .pipe(buffer())
      .pipe(gulp.dest(config.publicDir))
      .on('end', ->
        process.chdir(buildDir)
        cdv.prepare().then ->
          process.chdir(root)
      )

  watchify(bundler).on('update', bundle) if config.isDevelopment()
  bundle()

For proper libraries connection I'm using 'browserify-shim' package.

import 'backbone-routefilter';
import 'backbone-stickit';
import 'backbone-validation';
import 'backbone-nested-model';
import 'marionette';
import 'velocity-ui';
import {App} from 'scripts/app';

document.addEventListener('deviceready', (function() {
  let app = new App();
  app.start();
}), false);

Here the error:
screen shot 2015-02-22 at 23 03 35
screen shot 2015-02-22 at 23 04 09

@sebmck
Copy link

sebmck commented Feb 22, 2015

Try changing

.transform(babelify.configure(
  extensions: ['.js']
  sourceMapRelative: "./#{config.appDir}"
))

to

.transform(babelify.configure(
  ignore: "bower_components",
  extensions: ['.js']
  sourceMapRelative: "./#{config.appDir}"
))

@maratfakhreev
Copy link
Author

That works perfectly. Ashamed that I hadn't thought of before. Thank you!)

And minor question. Is there a way not to use 'remapify' and replace it with some integrated solution?

@sebmck
Copy link

sebmck commented Feb 23, 2015

I'm not familiar with remapify, what exactly do you want to do?

@maratfakhreev
Copy link
Author

It's just for using relative paths inside the modules.
For example if my module places in MyApp/app/scripts/views/view.js with remapify I can write smth like this:

import View from 'scripts/views/view'

instead of path from Node.js rootPath:

import View from '../../scripts/views/view'

@sebmck
Copy link

sebmck commented Feb 23, 2015

There's the option resolveModuleSource documented here.

@maratfakhreev
Copy link
Author

Could you please provide short example of this option using? It still doesn't work. (

@sebmck
Copy link

sebmck commented Mar 3, 2015

Just realised that you wont be able to do what you want since there's no filename argument called on resolveModuleSource so you wont be able to resolve the relative path. I'll add an additional filename argument now and it'll be available in the next release, sorry!

@jmm
Copy link
Member

jmm commented May 21, 2015

Looks like filename argument landed in babel-core v4.7.0 and babelify v5.0.5.

@sebmck It would've been possible before by returning an absolute path from resolveModuleSource(), right (with the caveat that the path would be exposed)?

@maratfakhreev Usage for you should be something like this I think:

var aliases = {
  scripts: '/abs/path/to/scripts',
  templates: '/abs/path/to/templates/',
};
babelify.configure({
  resolveModuleSource: function (id, parent) {
    var matches = id.split('/');
    if (aliases[matches[0]]) {
      id = id.replace(
        matches[0],
        path.relative(parent, aliases[matches[0]]))
      );
    }
    return id;
  },
})

As you probably know, remapify has all sorts of problems. Another alternative that may work for you is my pathmodify browserify plugin. (resolveModuleSource is certainly more integrated with babel / babelify, while pathmodify is a more general purpose solution for implementing this kind of behavior in browserify. pathmodify also will not change the value that appears in the source, but I think resolveModuleSource may.) Basic usage would look something like this:

var pathmod = require('pathmodify');
// ...
.plugin(pathmod(), {mods: [
  pathmod.mod.dir('scripts', '/abs/path/to/scripts'),
  pathmod.mod.dir('templates', '/abs/path/to/templates'),
]}

@maratfakhreev
Copy link
Author

Ohh, I solved this problem some time ago, here my working config (as you can see I don't use remapify or smth like it):

var gulp = require('gulp');
var rename = require('gulp-rename');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var browserifyShim = require('browserify-shim');
var jadeify = require('jadeify');
var babelify = require('babelify');
var watchify = require('watchify');
var notify = require('gulp-notify');
var cordovaPrepare = require('../helpers/cdv');
var config = require('../config');
var entryPoint = "./" + config.appDir + "/scripts/main.js";

gulp.task('browserify', function() {
  var bundler = browserify({
    cache: {},
    packageCache: {},
    fullPaths: true,
    debug: config.isDevelopment(),
    extensions: ['.jade', '.js'],
    entries: entryPoint,
    paths: ["./" + config.appDir]
  })
  .transform(browserifyShim)
  .transform(jadeify)
  .transform(babelify.configure({
    ignore: [
      'bower_components',
      'vendor/scripts'
    ],
    sourceMapRelative: "./" + config.appDir
  }));

  function bundle() {
    var bundleTransform = transform(function(filename) {
      return bundler.bundle();
    });

    return gulp.src(entryPoint)
      .pipe(bundleTransform)
      .on('error', notify.onError())
      .pipe(rename({basename: 'application'}))
      .pipe(gulp.dest(config.publicDir))
      .on('data', cordovaPrepare);
  };

  if (config.isDevelopment()) {
    watchify(bundler).on('update', bundle);
  };

  return bundle();
});

Btw thank you guys (@sebmck, @jmm) for supporting and for good advices. If there no questions you could close the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants