How to ignore libraries in browserify programmatic api - node.js

Assume the below code is found in bundler.js and tracing entry.js leads to var B = require('backbone'); (Backbone is a dependency installed as declared in package.json).
var browserify = require('browserify');
var bundle = new browserify();
bundle.add('entry.js');
bundle.bundle({
noParse: ['backbone']
});
Executing this bundler yields a stream that contains the original backbone source. Based on browserify's command line options I expected it to skip backbone alltogether. Reading through the source, I expected perhaps the following would work:
var browserify = require('browserify');
var bundle = new browserify({
noParse: ['backbone']
});
bundle.add('entry.js');
bundle.bundle();
Though backbone source still appears in the stream output.
Is it possible to use --noparse=FILE as a configuration option in this application of the api?

As you can see from here the --noparse option provided on the command line is passed to the browserify({ }) call.
So in order to tell browserify to not parse jquery and three.js you have to pass the full path to your jquery and three.js files.
Example:
browserify({
noParse: [
require.resolve('./vendor/jquery'),
require.resolve('./vendor/three')
]
})
.require(require.resolve('./entry.js'), { entry: true })
.bundle();

var browserify = require("browserify")
browserify({entries: ['./src/client/app.js']})
.ignore('jquery')
That would make browserify ignore jquery, and then jquery can be added on index.html directly.

Related

babelify pipe results in: The code generator has deoptimised the styling of "/.../jquery.js" as it exceeds the max of "100KB"

I'm trying to create a single js file containing jquery, bootstrap and reactjs components using a gulp task:
app.jsx:
var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = require('./Application.jsx');
var $, jQuery = require('../../libraries/jquery/dist/jquery');
var bootstrap = require('../../libraries/bootstrap-sass/assets/javascripts/bootstrap');
ReactDOM.render(
<Application />,
document.getElementById('example')
);
gulp task:
gulp.task('js', function () {
browserify('./public/javascripts/src/app.jsx')
.transform(babelify, {presets: ["es2015", "react"]})
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('public/javascripts/build/'));
});
When running gulp, I get the following message:
[BABEL] Note: The code generator has deoptimised the styling of "/Users/.../jquery/dist/jquery.js" as it exceeds the max of "100KB".
How I design the gulp task, so that jquery and bootstrap does not pass the babelify pipe?
One possible solution is to add an ignore key to your babelify configuration so that it looks like something along the lines of:
.transform(babelify, {ignore: ['./libraries/**/*'], presets:["es2015", "react"]})
This should keep bableify from messing with your lib files that are already es5/minified/production ready.
(You may need to adjust the path a little bit... not 100% of your project structure)

Browserify + Remapify (Gulp workflow)

I've successfully got Browserify to compile my JavaScript entry files, but I want to utilise the Remapify plugin so as to not have to specify the full relative path upon requiring a module every time.
For example:
require('components/tabs.js')
Rather than:
require('../../components/tabs/tabs.js').
But I cannot get the shorter module references to map to the corresponding file... "Error: Cannot find module [specified_ref] from [file]".
Have I misconfigured Remapify, or is there something wrong with my wider Browserify setup? I am new to Broswerify and Gulp having previously used Require.js and Grunt. Any help would be greatly appreciated. Please let me know if you need any more information about my setup.
If alternatively you can recommend an alternative Gulp task file that will do all of this, thereby throwing my current task out the window, by all means. I wasn't able to find many Browserify + Remapify examples.
Directory Structure
I have my modules (components) in the following directory: './src/components', so for example: './src/components/tabs/tabs.js'.
I am requiring these modules in a JS file for a given page of the app, which are in: './src/pages', so for example, './src/pages/portfolio/portfolio.js'.
Gulp Browserify Task
var gulp = require('gulp');
var config = require('../config');
var browserify = require('browserify');
var remapify = require('remapify');
var source = require('vinyl-source-stream');
var glob = require('glob');
var browserSync = require('browser-sync');
gulp.task('browserify', function(){
var entries = glob.sync(config.src.pages + '/**/*.js');
return browserify({
entries: entries,
debug: true
})
// (Remapify:)
.plugin(remapify, [{ src: config.src.components + '/**/*.js', expose: 'components', cwd: config.srcDir }])
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest(config.build.js))
.pipe(browserSync.reload({ stream: true }));
});
Page.js
'use strict';
var tabs = require('components/tabs.js'); // (Doesn't work, but I want it to)
// var tabs = require('../../components/tabs/tabs.js'); // (Does work)
Remapify has all sorts of problems. I suggest giving my pathmodify plugin a shot.
For your situation usage would look something like:
var pathmod = require('pathmodify');
// ...
.plugin(pathmod(), {mods: [
pathmod.mod.dir('components', '/path/to/src/components'),
]})

How can I use factor-bundle with browserify programmatically?

I want to use factor-bundle to find common dependencies for my browserify entry points and save them out into a single common bundle:
https://www.npmjs.org/package/factor-bundle
The factor-bundle documentation makes it seem very easy to do on the command line, but I want to do it programmatically and I'm struggling to get my head around it.
My current script is this (I'm using reactify to transform react's jsx files too):
var browserify = require('browserify');
var factor = require('factor-bundle')
var glob = require('glob');
glob('static/js/'/**/*.{js,jsx}', function (err, files) {
var bundle = browserify({
debug: true
});
files.forEach(function(f) {
bundle.add('./' + f);
});
bundle.transform(require('reactify'));
// factor-bundle code goes here?
var dest = fs.createWriteStream('./static/js/build/common.js');
var stream = bundle.bundle().pipe(dest);
});
I'm trying to figure out how to use factor-bundle as a plugin, and specify the desired output file for each of the input files (ie each entry in files)
This answer is pretty late, so it's likely you've either already found a solution or a work around for this question. I'm answering this as it's quite similar to my question.
I was able to get this working by using factor-bundle as a browserify plugin. I haven't tested your specific code, but the pattern should be the same:
var fs = require('fs'),
browserify = require('browserify'),
factor = require('factor-bundle');
var bundle = browserify({
entries: ['x.js', 'y.js', 'z.js'],
debug: true
});
// Group common dependencies
// -o outputs the entry files without the common dependencies
bundle.plugin('factor-bundle', {
o: ['./static/js/build/x.js',
'./static/js/build/y.js',
'./static/js/build/z.js']
});
// Create Write Stream
var dest = fs.createWriteStream('./static/js/build/common.js');
// Bundle
var stream = bundle.bundle().pipe(dest);
The factor-bundle plugin takes output options o which need to have the same indexes as the entry files.
Unfortunately, I haven't figured out how to do anything else with these files after this point because I can't seem to access factor-bundle's stream event. So for minification etc, it might need to be done also via a browserify plugin.
I have created grunt-reactify to allow you to have a bundle file for a JSX file, in order to make it easier to work with modular React components.
All what you have to do is to specify a parent destination folder and the source files:
grunt.initConfig({
reactify: {
'tmp': 'test/**/*.jsx'
},
})

Best practice for minifying TypeScript modules

I'm using requirejs and AMD modules for my TypeScript project, with something like 20 different source files at the moment and likely to grow substantially. All of this works, but it's very slow to load all 20 files, so it would be better to have them minified. But because of how requirejs wants to load everything, it seems like it's going to require that I keep the modules in separate files - I don't think I can just take the generated module1.js and module2.js files and minify them into one file and then have requirejs load those without changing some code. (I could be wrong on this.)
The other way that I see to do this is to use the r.js file that requirejs provides to merge all the different files together in a way that still keeps requirejs happy. But r.js requires node.js, and I'd rather not introduce that as a dependency in my build process if there's any other way to do it.
So before I dive into this and try half a dozen different solutions - how are other folks approaching this with big projects?
What you could do is to implement a thin RequireJS shim to use in a minified build. Depending on how much of the RequireJS API you want to use, you could get by with very little. For simplicity you could also use named modules.
Say, while developing you use RequireJS to load your modules. When you want to make a minified build, you could simply include a simple loader in the minified file.
If you have files app.js, foo.js and bar.js as follows:
//from app.js
define("app", ["foo", "bar"], function(foo, bar) {
return {
run: function() { alert(foo + bar); }
}
});
//from foo.js
define("foo", [], function() {
return "Hello ";
});
//from bar.js
define("bar", [], function() {
return "World!";
});
And let's say you minify all those files together. At the top of the file you include the following shim:
//from your-require-shim.js
(function(exports) {
var modules = {};
var define = function(name, dependencies, func) {
modules[name] = {
name:name,
dependencies:dependencies,
func:func,
result:undefined
};
};
var require = function(name) {
var module = modules[name];
//if we have cached result -> return
if(module.result) { return module.result; }
var deps = [];
//resolve all dependencies
for(var i=0,len=module.dependencies.length;i<len;i++) {
var depName = module.dependencies[i];
var dep = modules[depName];
if(!dep.result) {
//resolve dependency
require(depName);
}
deps.push(dep.result);
}
module.result = module.func.apply(this, deps );
return module.result;
};
exports.require = require;
exports.define = define;
}(window));
And execute the module defined in app.js
require("app").run();
Like in this fiddle.
It's a crude PoC of course, but I'm sure you get the meaning.
If you are using ASP.NET MVC 4, you can make a bundle which will minify everything when you deploy to production in a set of files or in a folder. You'll find more info on bundles here.

r.js optimizer resolving configured deps files

I try requireJS optimizer to pack all my scripts into one file and I cannot overcome one issue.
My requireJs configuration is
var require = {
// 'baseUrl': 'static/scripts',
'paths': {
'external': 'global/external'
},
'waitSeconds': 2,
// 'enforceDefine': true,
'deps': ['external/jquery-1.7.2'],
'config': {
}
};
requireJs will load everything that is in deps before it starts loading any other scripts. since jquery wraps itself with define function and with name jquery I can load it to my scripts simply by calling
var var $ = require('jquery');
This works great when code is not optimized.
PROBLEM:
when I run r.js (with node - but this I think is irrelevant) optimizer prints error that it cannot resolve jquery dependency.
There is nothing in requireJs optimizer faq on that. I tried play with configuring 'path' property but it didnt fix anything.
I removed deps property and added new element to paths
var require = {
// 'baseUrl': 'static/scripts',
'paths': {
'external': 'global/external'
'jquery': 'global/external/jquery-1.7.2'
},
'waitSeconds': 2,
...
};
it didnt play before because I tried to setup path to jquery like
'jquery': 'external/jquery-1.7.2'
thinking that external should evaluate to
'global/external/jquery-1.7.2'
then I just set path.jquery in build script (or as argument to r.js) once again and it worked

Resources