Gulp with browserify, tsify, and reactify? - javascript

I'm using gulp with browserify and tsify in a TypeScript project. The following is an extract from my gulpfile.js:
var browserified = function (filename, debug) {
var b = browserify({
entries: filename,
debug: debug || false
});
b.plugin('tsify', {
noImplicitAny: true,
target: 'ES5'
});
b.transform('debowerify');
return b.bundle();
};
gulp.task('rebuild', ['lint', 'less'], function() {
var b = browserified ('./src/ts/main.ts', true);
return buildSourceMaps (b);
});
This works so far. I want to extend this so I can require React JSX files. First I tried (from one of my TypeScript files):
import Test = require ('../jsx/Test.jsx');
This doesn't work, though, because tsify would complain as it looks for a TypeScript file ../jsx/Test.jsx.ts. So I use the following hack:
declare var require: any;
var Test = require ('../jsx/Test.jsx');
If Test.jsx is plain vanilla JavaScript, this works. If Test.jsx contains TypeScript, it would fail, which is what I expect. So far, so clear.
Now I want to add reactify to my gulp tasks so I can use JSX in these files. Here I am stuck! I tried adding the following to the function browserified in my gulpfile.js:
b.plugin ('reactify', {
extension: 'jsx'
});
I still get the following error when I call gulp rebuild when Test.jsx contains actual JSX:
Unexpected token <
Obviously, gulp chokes on the first JSX-specific term. I think gulp is trying to pass the JSX through the TypeScript compiler. Which isn't a surprise, since I can't think of a way how to tell tsify to ignore my .jsx files. I'm new to gulp, so I am a bit at a loss. Any ideas how to set up gulp to allow for TypeScript with all .ts files and JSX with all .jsx files?

This is the gulp task I use for development. It uses watchify along with browserify and reactify to build your code, provide source mapping, and rebundle any changes you make on the fly. The path.ENTRY_POINT variable is the main component for your react app (often app.js or main.js).
gulp.task('watch', function() {
gulp.watch(path.HTML, ['copy']);
var watcher = watchify(browserify({
entries: [path.ENTRY_POINT],
transform: [reactify],
debug: true,
cache: {}, packageCache: {}, fullPaths: true
}));
return watcher.on('update', function () {
watcher.bundle()
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_SRC))
console.log('Updated');
})
.bundle()
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_SRC));
});
I used this tutorial to set up my gulpfile.js and it provides a good explanation for every gulp task:
http://tylermcginnis.com/reactjs-tutorial-pt-2-building-react-applications-with-gulp-and-browserify/

Related

Browserify --standalone with ES6 modules and multiple source files and exports

I am trying to use Gulp, Browserify, and Babelify to compile and transform multiple ES6 files into a single JavaScript library that can be shared with other developers.
I am trying to use multiple ES6 source files, each of which uses ES6 modules using export. I want them all to be wrapped up into a single class/function like a 'namespace'.
It seems like Browserify's --standalone option is designed to do this, but I can only get it to work when there is a single input file. When there are multiple source files with exports, I can't get them all to be included in the 'namespace' class, and I can't control which source file's exports ultimately gets picked to be in the 'namespace' class.
In this example, a.js and b.js are the source files, and I am expecting them to be bundled together in a 'namespace' class called TestModule.
a.js
export function fromA() {
console.log('Hello from a.js');
}
b.js
export function fromB() {
console.log('Hello from b.js');
}
gulpfile.js
const browserify = require('browserify');
const gulp = require('gulp');
const log = require('gulplog');
const plumber = require('gulp-plumber');
const source = require('vinyl-source-stream');
function minimalExample(done) {
return browserify({
entries: [
'./src/a.js',
'./src/b.js'
],
standalone: 'TestModule' // output as a library under this namespace using a umd wrapper
})
.transform('babelify')
.bundle()
.on('error', log.error)
.pipe(source('minimalExample.js'))
.pipe(plumber())
.pipe(gulp.dest('./dist'));
}
module.exports = {
minimalExample
};
What I want
I want minimalExample.js to have an object named TestModule that has functions fromA() and fromB(), so that I can call both methods. I should be able to run either of these commands from the console:
TestModule.fromA()
TestModule.fromB()
What is actually happening
When I load minimalExample.js in a browser, open the console, and inspect the TestModule object, it exists, but it is missing the function from a.js. It only has the function from b.js:
Am I missing a setting somewhere? Is there a way to get Browserify to include all the exports in the standalone 'namespace' class?
Update 1
Prompted by #Zydnar's discussion, I did the obvious thing and actually looked at the output file, minimalExample.js. I don't understand how the transforms are intended to work or what is going wrong yet; I'm still looking at that. But I do see both input files have been transformed and included in the output.
Here is the actual output, and the same thing but pretty-printed by Chrome.
Thanks to help on the browserify project on Github, I have an answer for this. Renée Kooi pointed me in the right direction. They said:
If you have multiple entry points, all of them are executed, but browserify doesn't merge modules, which could cause bad unexpected behaviour.
The solution is to have a single file that acts as an entry point for Browserify that exports everything you want exported. Use that single file as your input source file in the entries option. Browserify will walk your app's dependency tree and include the dependencies it requires. Anything exported by the entry point file will be included in the exported module as expected.
A complete example follows. main.js is the entry point file.
a.js
export function fromA() {
console.log('Hello from a.js');
}
b.js
export function fromB() {
console.log('Hello from b.js');
}
main.js (This one is new)
export * from './a.js';
export * from './b.js';
gulpfile.js
const browserify = require('browserify');
const gulp = require('gulp');
const log = require('gulplog');
const plumber = require('gulp-plumber');
const source = require('vinyl-source-stream');
function minimalExample(done) {
return browserify({
entries: [
'./src/main.js' // THIS LINE HAS CHANGED FROM THE QUESTION
],
standalone: 'TestModule'
})
.transform('babelify')
.bundle()
.on('error', log.error)
.pipe(source('minimalExample.js'))
.pipe(plumber())
.pipe(gulp.dest('./dist'));
}
module.exports = {
minimalExample
};
Now when you run the minimalExample task with gulp, the file generated will have both TestModule.fromA() and TestModule.fromB() functions.

Bundling with webpack from script

I am using webpack to bundle my Javascript files in my project:
webpack --config myconfig.webpack.config.
From commandline it is ok.
Building
However I would like to create a build task, I am using jake, so in order to create the bundle I need to invoke webpack from Javascript.
I could not find the API online, I basically need something like this:
// Jakefile.js
var webpack = require("webpack");
desc('This is the default build task which also bundles stuff.');
task('default', function (params) {
webpack.bundle("path-to-config"); // Something like this?
});
How do I achieve this?
Attempt 1
I have tried the following:
// Jakefile.js
var webpack = require("webpack");
var config = require("./webpack.config.js");
desc('This is the default build task which also bundles stuff.');
task('default', function (params) {
webpack(config);
});
webpack.config.js is my config for webpack. When I use from commandline and reference that file the bundle is correctly created. But when using the above code it does not work. When I execute it, no errors, but the bundle is not emitted.
In your Attempt 1, you seem to be consuming the webpack's Node.js API by passing the config to webpack method. If you take this approach, webpack method will return a compiler object and you need to handle it correctly.
For e.g.,
import webpack from 'webpack';
var config = {}; // Your webpack config
var wpInstanceCompiler = webpack(config);
wpInstanceCompiler.run(function(err, stats) {
if (stats.hasErrors()) {
console.log(stats.toJson("verbose");
}
});
This is how you execute a webpack config via the Node.js API. Unless you run the compiler instance, the output will not get generated.
This worked for me as well:
var webpack = require("webpack");
var lib = require(path.join(__dirname, "webpack.config.js"));
desc('Builds the projects and generates the library.');
task('default', function() {
webpack(lib, function() {
console.log("Bundle successfully created!");
});
});

How do you load typescript modules from node_modules using browserify?

When I run tsc, everything runs perfectly fine. However, I cannot understand how you are meant to import other typescript modules from node modules.
This is the important part of my gulp file:
gulp.task('compile-ts', ['clean'], function(){
var sourceTsFiles = [
config.allTs,
config.typings
];
var bundler = browserify({
basedir : "src",
debug : true})
.add("app.ts")
//.add("typings/tsd.d.ts")
.plugin(tsify);
return bundler.bundle()
.pipe(source("bundle.js"))
.pipe(gulp.dest("build"))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write({includeContent: false, sourceRoot: 'src'}));
});
When I use,
import {DataRepository, List} from "tsmvc";
Where tsmvc is a typescript module node module, I get cannot find module tsmvc. Atom doesn't complain and shows me intellisense, tsc doesn't complain, but tsify does.
Can anyone point me to a gulp file doing something similar or explain the process?
Here's the github repo: https://github.com/Davste93/typescript-mvc-consumer/blob/master/gulpfile.js
Prior to version 0.15.3 of tsify, it was not possible to import TypeScript files from within node_modules.
Internally, the tsify plugin creates a transform and Browserify does not transform files under node_modules for non-global transforms. In version 0.15.3 of tsify, the global option was added and can be specified as follows:
var bundler = browserify({
basedir: "src",
debug: true
})
.add("app.ts")
.plugin(tsify, { global: true });

How to use both 'gulp-babel' and 'gulp-browserify'

I try to write these code
gulp.task('script', function() {
'use strict'
return gulp.src(['app.js', 'components/**/*.jsx'])
.pipe(babel())
.pipe(browserify())
.pipe(gulp.dest("dist"));
});
but it shows some error:
SyntaxError:
/Users/Zizy/Programming/learn-react-js/components/CommentBox.jsx:58
<div className="commentBox">
^
ParseError: Unexpected token
at wrapWithPluginError (/Users/Zizy/Programming/learn-react-js/node_modules/gulp-browserify/index.js:44:10)
It seems that before .pipe(browserify()) the gulp did't transform the jsx code. But if I just remove .pipe(browserify()) I find that did transform, just cannot let babel and browserify work together.
I know maybe I can use like babelify or browserify plugin for babel though, I just want figure out the reason.
gulp-browserify doesn't quite work like that. You don't give it a bunch of buffers to collect and bundle.
You give it one file—the entry file—which it passes into Browserify. Browserify checks to see what other files the entry file references, then loads those files directly from the file system, meaning that you can't modify them with gulp plugins beforehand.
So, really, if we pretend you don't want to use Babel on your source files, your gulpfile should look like this, only passing in the entry file:
gulp.task('script', function() {
'use strict'
return gulp.src('app.js')
.pipe(browserify())
.pipe(gulp.dest("dist"));
});
However, note that gulp-browserify is no longer maintained, and this is exactly why. gulp plugins aren't supposed to read directly from the file system. That's why you're supposed to use Browserify (or, in your case, Babelify) directly with vinyl-source-stream as recommended in the gulp recipes. It's more idiomatic and less confusing.
That wraps up my answer to your question, but I'd like to add: if you're using the ES2015 module syntax (and you probably should be), there's a better way to do this. Browserify wraps all your modules separately in a bunch of code to make the programmatic CommonJS API work properly, but ES2015 modules have a declarative syntax, which makes it much easier for tools to operate on them statically. There's a tool called Rollup that takes advantage of this, allowing it to produce bundles that are smaller, faster, and more minfication-friendly than Browserify's.
Here's how you might use it with gulp:
var gulp = require('gulp'),
rollup = require('rollup-stream'),
babel = require('gulp-babel'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer');
gulp.task('script', function() {
return rollup({entry: 'app.js'})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(babel())
.pipe(gulp.dest('dist'));
});
Starting from Babel 6 you need to declare the presets manually, check this.
Basically, in the root of your project you need a .babelrc with the following content:
{
"presets": [ "es2015", "react" ]
}
And the corresponding npm modules in package.json:
// package.json
{
"devDependencies": {
...
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18",
...
}
}
Here is a sample repository with gulp, babel and browserify
Following is the code snippet
gulp.task("js", (done) => {
const bundler = browserify({ entries: paths.js.source }, { debug: true }).transform(babel);
bundler.bundle()
.on("error", function (err) { console.error(err); this.emit("end"); })
.pipe(source(paths.build.destMinJSFileName))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(sourcemaps.write(paths.js.destMapFolder))
.pipe(gulp.dest(paths.build.destBuildFolder));
done();
});

how does the ignore parameter works in gulp and nodemon?

I'm trying to create a gulpfile that lint my personal javascript files (.js) but ignore any vendor/third party libaries.
My gulp file is listed below:
var gulp = require("gulp"),
uglify = require("gulp-uglify"),
jshint = require("gulp-jshint"),
jasmine = require("gulp-jasmine"),
nodemon = require("gulp-nodemon");
// lint JS files for bad habbits
gulp.task("lint", function () {
gulp.src(["**/*.js", "node_modules/*"])
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("nodemon", function () {
nodemon({
script: "server.js",
ext: "html css jade js",
ignore: ["node_modules/*"]
})
.on("change", ["lint"])
.on("restart", function () {
console.log("Change detected, restarting server ...");
});
});
gulp.task("default",["nodemon"]);
When I run the "gulp default" command in my terminal it still lint the javascript files in the node_modules. I've tried variations of the glob syntax but I can't seem to achieve the desired behaviour.
Any idea where I've gone wrong?
Thanks.
The glob pattern you've set, node_modules/* only matches the files in the root of the node_modules directory, but not all the children with an highter depth.
You need to set is as node_modules/**/*, this will match everything. I advice you however to only match js files, with node_modules/**/*.js.
You also need to negate the pattern with !, gulp does not know that you want to do that, so it will look like:
gulp.src(['**/*.js', '!node_modules/**/*.js'])
For nodemon, following the same thing you can use the node_modules/**/* pattern.
The library used by gulp for globbing is minimatch.
use this ignore: ["node_modules/"] without '*' and it will work

Categories

Resources