Using gulp-babel gives Uncaught ReferenceError: require is not defined - reactjs

I am using the following gulp.js file
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task('bundle', bundle);
function bundle () {
gulp.src('./src/*.jsx')
.pipe(babel())
.pipe(gulp.dest('./dist'));
}
gulp.task('build', ['bundle']);
Before transpile "main.jsx" content
import React from 'react';
After Transpile, "js" files generated in the dist folder, has require('')
var _react = require('react');
while requesting for the page index.html
<body>
<div id="app" ></div>
<script src="main.js"></script>
</body>
Uncaught ReferenceError: require is not defined is shown in the console.
I know there is something wrong in the build task, but i am unable to figure out.

In the browser, you can not use require API, so you need to somehow bundle your code, you have few options:
Browserify
Webpack
Rollup
These module bundlers allow you to specify an 'entry' point and then bundle all the required modules together in a single file.
Similar questions that answer this problem:
Gulp + babelify + browserify issue

Related

Webpack Unable to bundle two controllers in single file

I am using webpack to bundle my files with angular 1.x
ON making bundle facing the issue that is
my first file is app.js where I write
var sampleApp = angular.module('kinatorApp', ['ui.router','ngCookies','oc.lazyLoad','ngResource','ngDraggable','restangular','oi.select','ui.bootstrap','toastr','LocalStorageModule','ngMessages','ngMaterial','ngScrollable']);
and my second file is parentController.js
where my code is
sampleApp.controller("parentCtrl", ['$scope','$rootScope','$compile','$http','$filter','$state','userServices','labelServices','sharedValues','groupServices','channelListService','parentControllerServices','toastr','positioningDataServices','$mdDialog', '$mdMedia', '$window','notification',
function($scope,$rootScope,$compile,$http,$filter,$state,userServices,labelServices,sharedValues,groupServices,channelListService,parentControllerServices,toastr,positioningDataServices,$mdDialog, $mdMedia, $window,notification) {}]);
IN webpack I include these two files by
require('./public/app.js');
require('./public/ParentController.js');
my bundle is successfully made by on load it in index.html it says
Uncaught ReferenceError: sampleApp is not defined
at Object.<anonymous> (bundle.js:471)
at Object.122 (bundle.js:1200)
at __webpack_require__ (vendor.js:55)
at Object.120 (bundle.js:13)
at __webpack_require__ (vendor.js:55)
at webpackJsonpCallback (vendor.js:26)
at bundle.js:1
Unable to get sampleApp from app.js file in bundle
then I made sampleApp a global variable by
externals: {
'sampleApp': ''
}
But it also did,t work
I am using angular 1.x

Reactjs file size: script-file vs npm-version

I am using reactjs and gulp for the build-process. Currently I use react from npm with browserify. When I want to minify my App in production-mode the react code ends up with about 180kb.
This is the gulp code I use:
gulp.task('production', function () {
var bundler = browserify('./public/dev/js/main.js').transform(babelify, { presets: ['react'] });
return bundler.bundle()
.on('error', map_error)
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(rename('bundle-build.min.js'))
.pipe(envify({'_': 'purge', NODE_ENV: 'production'}))
.pipe(uglify())
.pipe(gulp.dest('./public/dist/js/'));
});
However, if I download the minified script files from the react-website and load the script files like this:
<script type="text/javascript" src="./react.min.js"></script>
<script type="text/javascript" src="./react-dom.min.js"></script>
it ends up with about 150kb.
Why is the with gulp minified version bigger? How can I bring it to the same size? Also, is there a difference in the development / production of the app between loading the provided script files or using it from npm?
Thanks in advance
Cheers

TSIFY compatibility with Typescript AngularJS

I am trying to build a gulp based process that would use AngularJS from a bower package and a tool called debowerify (which I believe should let me plug in the installed bower components into the TSIFY/Browserify stream). Essentially, I want to build an app.js file for use in my application (with all the JS I need). I cannot for the life of me get AngularJS to work in this process. I am using an index.ts file (see below) to bring in my references for browserify to work with. It has been tricky with angular as the library is optimized out by the compilation process unless you use the import in some way hence the module call I was testing in the index.ts file.
index.ts
//#### Type Definitions ####
/// <reference path="../../typings/angularjs/angular.d.ts" />
/// <reference path="greeter.ts" />
import angular = require('angular');
import greeter = require('./Greeter');
var greet = new greeter();
greet.sayHello();
angular.module('app', []);
Here are my gulp defintions:
gulpfile.js
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var tsify = require('tsify');
var debowerify = require('debowerify');
var exorcist = require('exorcist');
var config = {
publicDir: __dirname + '/app',
path: __dirname + '/src/typescript',
main: 'index.ts',
result: 'app.js'
};
gulp.task('compile-ts', function(){
var bundler = browserify({
basedir: config.path,
debug: true
})
.add(config.path + '/' + config.main)
.plugin(tsify)
.transform(debowerify);
return bundler.bundle()
.pipe(exorcist(config.publicDir + '/app.js.map'))
.pipe(source(config.result))
.pipe(gulp.dest(config.publicDir));
});
The custom TS files I built (ie: greeter.ts) work great. However, when I run my gulp compile-ts task I get no errors in the console only in the browser when it informs me that angular is undefined (on the call to angular.module). I have suspicions that CommonJS may not be supported for angular, but I also found information on the interwebs to the contrary of that. I am trying to avoid AMD if possible but if that is my only option I would certainly re-consider. I have this application working if I link to the angular script in my html rather than attempt to import it into my typescript, but I am just not satisfied with that approach as I know this should work.
Angular doesn't currently support CommonJS, replacing
import angular = require('angular');
with
require('angular');
solved it for me. See here.

Getting browserify to work with angular

My app.js looks like below:
//app.js
var angular = require('angular');
angular.module('app', []);
angular.module('app').controller('MainCtrl', function ($scope) {
$scope.test = "abc";
});
//index.html
<body ng-app="app" ng-controller="MainCtrl">
{{test}}
<script src="dist/app.js"></script>
</body>
The directory structure is as follows:
app/
index.html
app.js
node_modules/
angular/
Angular was installed using npm install.
I then compile the code using the following command:
browserify --entry app.js --outfile dist/app.js
Then upon opening the file index.html in the browser I get the following errors:
Uncaught TypeError: undefined is not a function
angular.module('app', []);
Further errors:
2014-11-30 19:44:46.345app.js:4082 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument
What could i be missing ?
.
Finally figured it out.
What had to be done is as below:
Create a angular-index.js file in node_modules/angular folder
Contents of this file are as below:
require('./angular.min.js');
module.exports = angular;
Then include this file in the browser option of the package.json file.
How exactly this makes things work I am not yet sure.. but this got the code rolling.

HTML minification via Gulp.js is breaking my Chart.js chart in my Angular app

I am just learning Gulp and trying to get it all working with my Angularjs app.
I have successfully concatenated & minified my JS files and minified my html files using the gulpfile.js below. App works great, but my only problem is my chart does not show up after minifying my HTML. I am using the latest version of chartjs with the Angles wrapper for angularjs. (https://github.com/lgsilver/angles)
gulpfile.js
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
ngAnnotate = require('gulp-ng-annotate'),
minifyHTML = require('gulp-minify-html'),
connect = require('gulp-connect'),
htmlify = require('gulp-angular-htmlify');
// compact js
gulp.task('js', function () {
gulp.src(['app/assets/js/**/app.js', 'app/assets/js/**/*.js'])
.pipe(concat('app.js'))
.pipe(ngAnnotate())
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('dist/assets/js'))
});
//compact html
gulp.task('html', function() {
gulp.src(['app/*.html', 'app/**/*.html'])
.pipe(htmlify())
.pipe(minifyHTML())
.pipe(gulp.dest('dist'))
});
my original html
<div id="home-chart">
<canvas barchart options="chartOptions" data="chartData" width="700" height="170"></canvas>
</div>
my minified html
<div id=home-chart><canvas options=chartOptions data=chartData width=700 height=170></canvas></div>
I am not getting any errors, only a blank space where my bar chart should be.
Is this a problem with my javascript or the minified html?
Looks like gulp-minify-html (or rather the module it uses minimize) removes attributes without values by default.
You can easily fix that: .pipe(minifyHTML()) => .pipe(minifyHTML({empty: true}))

Resources