Related
I try to build my React project with gulpfile.js in production mode so the query developer tools show green color in browser tab. However, it still failed with dead code elimination error, which means development version is still detected in react developer tools.
I have already tried many ways to eliminate this error. One of the closest solution is to add 'unreachable-branch-transform' and gulpif argv in browserify part in gulpfile.js. Please check gulpfile.js content below.
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var clean = require('gulp-clean');
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var envify = require('envify/custom');
var replace = require('gulp-replace');
var gutil = require('gulp-util');
var uglifyCSS = require('gulp-uglifycss');
var uglifyJS = require('gulp-uglify');
var version_append = require('gulp-version-append');
var connect = require('gulp-connect');
var historyApiFallback = require('connect-history-api-fallback');
var workboxBuild = require('workbox-build');
var prefixer = require('autoprefixer');
var postcss = require('gulp-postcss');
var concat = require('gulp-concat');
var less = require('gulp-less');
var chalk = require("chalk");
var path = require('path');
var exec = require('child_process').exec;
var paths = {
public_view_src : "view/",
public_view_dest : "public/",
images: 'img/**/*',
css :
[
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/font-awesome/css/font-awesome.min.css",
"node_modules/animate.css/animate.min.css",
"node_modules/lato-font/css/lato-font.min.css"
],
js :
{
plugins: [
"node_modules/clientjs/dist/client.min.js",
"node_modules/jquery.payment/lib/jquery.payment.min.js"
],
vendor: [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
react : ["./src/app.js", "./src/**/*.js"],
app: "./script/*.js",
register_service_worker: 'service_worker/register_service_worker.js'
},
fonts : [
"node_modules/font-awesome/fonts/**/*",
"node_modules/bootstrap/dist/fonts/**/*"
],
less : ["less/style.less", "less/**/*.less", "node_modules/roboto-fontface-pre-css/css/roboto-fontface.less"],
service_worker: 'service_worker/service-worker.js'
};
function build_service_worker() {
console.info('Workbox libraries copying started.');
return workboxBuild.copyWorkboxLibraries(paths.public_view_dest).then((workboxDirectoryName) => {
console.info('Workbox libraries copied to: ' + workboxDirectoryName);
return workboxBuild.injectManifest({
swSrc: `${paths.service_worker}`,
swDest: `${paths.public_view_dest}/service-worker.js`,
maximumFileSizeToCacheInBytes: 50000000,
globDirectory: paths.public_view_dest,
globPatterns: ['**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'],
globIgnores: ['service-worker.js', 'manifest.json'].concat([`**/workbox*/*.js*`])
}).then((result) => {
result.warnings.forEach(console.warn);
console.info(`${result.count} files will be precached, totaling ${result.size} bytes.`);
console.info(`import ${paths.public_view_dest}${workboxDirectoryName}/workbox-sw.js to service-worker-script`);
gulp.src(`${paths.public_view_dest}/service-worker.js`)
.pipe(replace('#workbox-sw', `${workboxDirectoryName}/workbox-sw.js`))
.pipe(gulp.dest(paths.public_view_dest));
console.info('Service worker generation completed.');
});
}).catch((error) => {
console.warn('Workbox lbraries copying failed: ' + error);
});
}
// map error
function map_error(err) {
if (err.fileName) {
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(err.fileName.replace(__dirname, ''))
+ ': '
+ 'Line '
+ chalk.magenta(err.lineNumber)
+ ' & '
+ 'Column '
+ chalk.magenta(err.columnNumber || err.column)
+ ': '
+ chalk.blue(err.description));
} else {
var message = err.message.replace(__dirname + "/", "");
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(message));
}
this.emit('end');
}
function prevent_cache_assets(){
return function(){
return gulp.src(path.join(__dirname, paths.public_view_src + '*.html'))
.pipe(version_append(['html', 'js', 'css'],
{
appendType: 'timestamp',
versionFile: 'version.json'
}))
.pipe(gulp.dest(paths.public_view_dest));
};
}
function reactScript(watch) {
var bundler, rebundle;
bundler = browserify(paths.js.react[0], {
basedir: __dirname,
// debug: watch,
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: watch, // required to be true only for watchify
debug: argv.production ? false : true
});
if(watch) {
bundler = watchify(bundler);
}
bundler.transform('unreachable-branch-transform', {
global: true
});
bundler.transform(envify({
_: 'purge',
MODE: process.env.MODE
}));
bundler.transform(babelify.configure({
"plugins": ["object-assign"]
}));
rebundle = function() {
console.log("packing react");
var stream = bundler.bundle();
stream.on('error', map_error);
stream = stream.pipe(source('app.min.js'));
if(!watch) {
stream = stream.pipe(gulpif(argv.production, buffer()));
//stream = stream.pipe(uglifyJS());
}
return stream.pipe(gulp.dest('public/assets/dist'));
};
bundler.on('update', rebundle);
bundler.on('log', gutil.log);
return rebundle();
}
function es(){
return gulp.src('public/assets/dist/app.min.js')
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/dist'));
}
gulp.task('mini', es);
// task for stage or production
gulp.task('min', ['js', 'vendor', 'less', 'copyfonts', 'prevent_cache_assets']);
// init task
gulp.task('init', ['js', 'vendor', 'less', 'copyfonts', 'watch', 'prevent_cache_assets'], function () {
gulp.watch([paths.public_view_src + '**\/*', paths.service_worker, paths.public_view_dest + 'assets/**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'], ['build-service-worker']);
return build_service_worker();
});
// imagemin
gulp.task('clean-images-dest', function(){
return gulp.src('public/assets/img', {read: false})
.pipe(clean());
});
gulp.task('images', ['clean-images-dest'], function(){
return gulp.src(paths.images)
.pipe(imagemin())
.pipe(gulp.dest('public/assets/img'));
});
// react
gulp.task('react', function () {
return reactScript(false);
});
// copy fontawesome fonts task
gulp.task('copyfonts', function() {
return gulp.src(paths.fonts)
.on('error', map_error)
.pipe(gulp.dest('public/assets/css/fonts'));
});
// less task
gulp.task('less', ['images'], function(){
var l = less();
l.on('error', map_error);
return gulp.src(paths.less[0])
.pipe(l)
.pipe(postcss([prefixer({ browsers: ["> 0%"] })]))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css'));
});
// copy lato fonts
gulp.task('cp-myriad-font', function(){
return gulp.src(['./node_modules/myriad-font/fonts/myriad/myriad-set-pro_text.woff', './node_modules/myriad-font/fonts/myriad/myriad-set-pro_bold.woff'])
.pipe(gulp.dest('public/assets/css/fonts'));
});
// vendor task
gulp.task('vendor', ['cp-myriad-font'], function(){
return gulp.src(paths.css)
.on('error', map_error)
.pipe(concat('vendor.css'))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css/vendor'));
});
// prevent cache task
gulp.task('prevent_cache_assets', prevent_cache_assets());
// javascript task
gulp.task('js', ['js_vendor', 'js_plugins', 'js_register_service_worker'], function(){
return gulp.src(paths.js.app)
.on('error', map_error)
.pipe(concat('app.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_vendor', function(){
return gulp.src(paths.js.vendor)
.on('error', map_error)
.pipe(concat('vendor.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_plugins', function(){
return gulp.src(paths.js.plugins)
.on('error', map_error)
.pipe(concat('plugins.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_register_service_worker', function(){
return gulp.src(paths.js.register_service_worker)
.on('error', map_error)
.pipe(concat('register_service_worker.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
// task to run api
gulp.task('api', function(cb){
exec('cd ../mp-wallet-api && nodemon', function(err, stdout, stderr){
console.log(stdout);
console.log(stderr);
cb(err);
});
});
// watcher
gulp.task('watch', function(){
gulp.watch(paths.less, ['less']);
gulp.watch(paths.js.app, ['js']);
gulp.watch(paths.js.plugins, ['js']);
gulp.watch(paths.js.vendor, ['js']);
gulp.watch(paths.js.register_service_worker, ['js']);
gulp.watch(paths.css, ['vendor']);
gulp.watch(paths.fonts, ['copyfonts']);
gulp.watch(paths.public_view_src + '*.html', ['prevent_cache_assets']);
return reactScript(true);
});
gulp.task('connect', function() {
connect.server({
port: 3000,
root: [paths.public_view_dest],
middleware: function(connect, opt){
return [historyApiFallback({})];
},
fallback: 'index.html'
});
connect.serverClose();
});
gulp.task('set-production-env', function() {
return process.env.NODE_ENV = 'production';
});
gulp.task('default', ['set-production-env', 'init']);
gulp.task('serve', ['set-production-env', 'init', 'connect']);
gulp.task('with-api', ['set-production-env', 'api', 'init']);
gulp.task('build-service-worker', function () {
return build_service_worker();
});
My React project is only using gulp and browserify inside gulpfile.js, so this project doesn't use any build tools listed in documentation link below (grunt, webpack, browserify (standalone),rollup).
https://reactjs.org/docs/optimizing-performance.html
Do you have any suggestion how to eliminate dead code elimination, but only by using gulp and browserify inside it ? Thanks in advance.
Integrating GULP with my React Project. On firing up the project, the following is the error that I face: https://prnt.sc/trw1if
Do check the screenshot above. This is a particular issue that I face.
Do let me know what am I doing wrong here. I've tried different presets for it as well. I am also attaching my GULP file here:
var gulp = require('gulp');
var babel = require('gulp-babel');
var sass = require('gulp-sass');
const imagemin = require('gulp-imagemin');
var concat = require('gulp-concat');
var uglify = require("gulp-uglify");
var browserSync = require("browser-sync").create();
const rollup = require('gulp-better-rollup');
// const babel = require('rollup-plugin-babel');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
gulp.task('jsCompile', function () {
return gulp.src(['src/*.js', 'src/**/*.js', 'src/**/**/*.js'])
.pipe(babel({
presets: ['#babel/preset-react', '#babel/preset-env']
})
.on('error', function (err) {
console.log('[Compilation Error]');
console.log(err.fileName + (err.loc ? `( ${err.loc.line}, ${err.loc.column} ): ` : ': '));
console.log('error Babel: ' + err.message + '\n');
console.log(err.codeFrame);
this.emit('end');
}))
// .pipe(rollup({ plugins: [babel(), resolve(), commonjs()] }, 'umd'))
.pipe(uglify())
.pipe(concat('main.js'))
.pipe(gulp.dest('dist/js'))
.pipe(browserSync.stream())
});
gulp.task('htmlCompile', function () {
return gulp.src(['public/*.html'])
.pipe(gulp.dest('dist/'))
});
gulp.task('sassCompile', function () {
return gulp.src(['src/*.scss', 'src/*.css'])
.pipe(concat('main.css'))
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('dist/css'))
});
gulp.task('imageCompile', function () {
return gulp.src(['src/assets/images/*.jpg', 'src/assets/images/*.png'])
.pipe(imagemin())
.pipe(gulp.dest('dist/assets'))
});
gulp.task('broswerReload', function () {
browserSync.init(["dist/css/*.css", "dist/js/*.js"], {
server: {
baseDir: "./dist"
}
})
});
gulp.task('serve', gulp.parallel('jsCompile', 'htmlCompile', 'imageCompile', 'broswerReload'), function () {
// gulp.watch(['src/*.scss', 'src/*.css'], ['sassCompile']);
gulp.watch('src/*.js', ['jsCompile']);
gulp.watch(['src/assets/images/*.jpg', 'src/assets/images/*.png'], ['imageCompile']);
gulp.watch('public/*.html', ['htmlCompile'])
// gulp.watch('public/*.html', ['htmlCompile']).on('change', browserSync.reload);
});
gulp.task('default', gulp.series('serve'));
I have a project which used Gulp 3 + Node 11 (The project is AngularJS with the basic webpack + babel etc ...).
The need arose to migrate to Gulp 4 + Node 12. I changed the syntax from Gulp 3 to 4, the command "gulp build" is running, the console appears that everything is ok.
But when I try to access the application it says that:
Uncaught ReferenceError: require is not defined
at eval (eval at globalEval (jquery.js:2)
This error is repeated with other libs as well.
Below a part of my gulp.js, the calls part, probably the error is here. I think I'm getting complicated in this business of having to force sync on gulp 4, which I didn't have on Gulp 3.
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var simplevars = require('postcss-simple-vars');
var nested = require('postcss-nested');
var mqPacker = require('css-mqpacker');
var cssnano = require('cssnano');
var cssimport = require('postcss-import');
var usemin = require('gulp-usemin');
var fs = require('graceful-fs');
var open = require('open');
var rename = require('gulp-rename');
var minifyCss = require('gulp-clean-css');
// var gulpsync = require('gulp-sync')(gulp);
var express = require('express');
var uglify = require('gulp-uglify');
// /* ES6 */
var replace = require('gulp-replace');
var gulpif = require('gulp-if');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');
var babelify = require('babelify');
var _ = require('lodash');
var through = require('through');
var livereload = require('gulp-livereload');
var fn = require('gulp-fn');
var notify = require('gulp-notify');
var templateCache = require('gulp-angular-templatecache');
function ErrorHandler() {
var args = Array.prototype.slice.call(arguments);
notify.onError({
title: "Compile Error",
message: "<%= error.message %>"
}).apply(this, args);
this.emit('end');
};
var envConfig = process.env.CONFIG || 'development';
var filename = envConfig + '.json';
var settings = JSON.parse(fs.readFileSync('./config/' + filename, 'utf8'));
var isMinify = !!settings.minify;
settings.buildVersion = new Date().getTime();
var PORT = process.env.PORT || 3000;
var PATH = {
js: {
src: 'src/**/*.js',
dest: 'build'
},
styles: {
src: 'src/core/styles/common.css',
srcWatch: 'src/**/*.css',
dest: 'build/core/styles/'
},
images: {
src: ['src/**/*.png', 'src/**/*.jpg', 'src/**/*.svg', 'src/**/*.pdf', 'src/**/*.ico'],
dest: 'build'
},
fonts: {
src: ['src/core/fonts/**/*.eot', 'src/core/fonts/**/*.ijmap', 'src/core/fonts/**/*.svg', 'src/core/fonts/**/*.ttf', 'src/core/fonts/**/*.woff', 'src/core/fonts/**/*.woff2'],
dest: 'build'
},
fontsAwesome: {
src: ['node_modules/font-awesome/fonts/*.*'],
dest: 'build/lib/fonts'
},
html: {
src: 'src/**/*.html',
dest: 'build'
},
usemin: {
src: 'src/index.tmpl',
dest: 'build'
},
windows: {
srcPaste: '../../../inetpub/wwwroot/app',
srcCopy: 'build/**/*.*',
srcWebConfig: 'web.config'
}
};
function replaceKeys() {
return replace(/(#{2}[A-z,0-9]+)/g, function (key) {
return settings[key.slice(2)];
});
}
async function compileTemplateIndex() {
gulp
.src(PATH.usemin.src)
.pipe(rename('index.html'))
.pipe(replaceKeys())
.pipe(usemin({
assetsDir: '.',
css: ['concat'],
js: ['concat']
}))
.pipe(gulp.dest(PATH.usemin.dest));
}
async function copyFonts() {
gulp
.src(PATH.fonts.src)
.pipe(gulp.dest(PATH.fonts.dest));
}
async function copyFontsAwesome() {
gulp
.src(PATH.fontsAwesome.src)
.pipe(gulp.dest(PATH.fontsAwesome.dest));
}
async function copyImages(done) {
gulp
.src(PATH.images.src)
.pipe(gulp.dest(PATH.images.dest));
done()
}
async function copyImagesUI() {
gulp
.src('bower_components/jquery-ui/themes/base/images/**/*')
.pipe(gulp.dest('build/lib/css/images'));
}
async function compileHtml() {
return gulp.src(PATH.html.src)
.pipe(replaceKeys())
.pipe(templateCache({
standalone: true
}))
.pipe(gulp.dest(PATH.html.dest));
}
async function compilePostCss() {
var processors = [
cssimport,
simplevars,
nested,
mqPacker,
autoprefixer
];
if ( isMinify ) processors.push(cssnano({
discardComments: {
removeAll: true
},
zindex: false
}));
return gulp
.src(PATH.styles.src)
.pipe(postcss(processors))
.pipe(gulp.dest(PATH.styles.dest));
}
function transformKeys(file) {
var data = '';
return through(write, end);
function write(buf) {
data += buf
}
function end() {
data = data.replace(/(#{2}[A-z,0-9]+)/g, function (key) {
return settings[key.slice(2)];
})
this.queue(data);
this.queue(null);
}
}
async function compileEs6() {
compileEs6_Bundle(false, './src/app.js', 'app.js');
// compileEs6_Bundle(false, './src/components/components.module.js', 'components.js');
// compileEs6_Bundle(false, './src/modules/modules.module.js', 'modules.js');
}
function compileEs6_watch() {
compileEs6_Bundle(true, './src/app.js', 'app.js');
// compileEs6_Bundle(true, './src/components/components.module.js', 'components.js');
// compileEs6_Bundle(true, './src/modules/modules.module.js', 'modules.js');
}
function compileEs6_Bundle(watch, src, dest) {
var bro;
var src = src || './src/app.js';
var dest = dest || 'app.js';
if (watch) {
livereload.listen();
bro = watchify(browserify(_.assign(watchify.args, {
entries: [src],
debug: true
})));
bro.on('update', function (file) {
console.log(file + ' changed');
rebundle(bro);
});
} else {
bro = browserify(src, {
debug: true
});
}
bro.transform(babelify.configure({
compact: false,
presets: ['#babel/env'],
}));
bro.transform(transformKeys);
function rebundle(bundler) {
return bundler.bundle()
.on('error', ErrorHandler)
.pipe(source(dest))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write())
.pipe(gulpif(isMinify,
uglify({
mangle: false
})
))
.pipe(gulp.dest('./build'))
.pipe(gulpif(watch, fn(
function () {
livereload.reload();
openServer();
}
)));
}
return rebundle(bro);
}
async function watch() {
livereload.listen();
function livereloadNotify(e) {
livereload.changed(e.path);
}
var onChanged = _.debounce(livereloadNotify, 600);
/* listen js files */
compileEs6_watch();
gulp.watch(PATH.images.src, gulp.series(['copy-images'])).on('change', onChanged);
gulp.watch(PATH.styles.srcWatch, gulp.series(['postcss'])).on('change', onChanged);
gulp.watch(PATH.html.src, gulp.series(['html'])).on('change', onChanged);
gulp.watch(PATH.usemin.src, gulp.series(['compile-template-index'])).on('change', onChanged);
}
async function webserver() {
var app = express();
app.use(express.static('build'));
var server = app.listen(PORT, function () {
console.log('Listening on port %d', PORT);
});
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/build/index.html');
});
}
function openServer() {
//open('http://localhost:'+ PORT +'/');
//openServer = function () {};
}
function copyFilesToBuildFolder() {
function rmDir(dirPath) {
try { var files = fs.readdirSync(dirPath); }
catch(e) { return; }
if (files.length > 0){
for (var i = 0; i < files.length; i++) {
var filePath = dirPath + '/' + files[i];
if (fs.statSync(filePath).isFile()){
fs.unlinkSync(filePath);
} else {
rmDir(filePath);
}
}
}
fs.rmdirSync(dirPath);
}
rmDir(PATH.windows.srcPaste);
gulp
.src(PATH.windows.srcCopy)
.pipe(gulp.dest(PATH.windows.srcPaste));
gulp
.src(PATH.windows.srcWebConfig)
.pipe(gulp.dest(PATH.windows.srcPaste));
}
gulp.task('compile-es6', compileEs6);
gulp.task('compile-template-index', compileTemplateIndex);
gulp.task('copy-images', copyImages);
gulp.task('copy-fonts', copyFonts);
gulp.task('copy-fonts-awesome', copyFontsAwesome);
gulp.task('copy-images-ui', copyImagesUI);
gulp.task('html', compileHtml);
gulp.task('postcss', compilePostCss);
gulp.task('watch', watch);
gulp.task('server', webserver);
gulp.task('copy-files-to-build-folder', copyFilesToBuildFolder);
gulp.task('build', gulp.series(['copy-fonts','copy-fonts-awesome','copy-images-ui','postcss','copy-images','compile-template-index','html','compile-es6']));
gulp.task('serve', gulp.series(['build','server','watch']));
// gulp.task('build-sv-windows', gulpsync.sync(['build', 'copy-files-to-build-folder']));
This is my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');
var del = require('del');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var htmlmin = require('gulp-htmlmin');
var ngAnnotate = require('gulp-ng-annotate');
var sourcemaps = require('gulp-sourcemaps');
var paths = {
html: {entry: ['public/angular/entry.html'], partials: ['public/angular/partials/**/*.html'], views: ['public/angular/views/**/*.html']},
dist: 'public/dist',
bower_components: ['bower_components/jquery/dist/jquery.min.js', 'bower_components/jquery.cookie/jquery.cookie.js', 'bower_components/bootstrap/dist/js/bootstrap.min.js', 'bower_components/jquery.nicescroll/jquery.nicescroll.min.js','bower_components/jquery-sparkline/dist/jquery.sparkline.min.js', 'bower_components/jquery.easing/jquery.easing.min.js', 'bower_components/bootbox.js/bootbox.js', 'bower_components/retina.js/dist/retina.min.js', 'bower_components/angular/angular.min.js', 'bower_components/angular-sanitize/angular-sanitize.min.js', 'bower_components/angular-touch/angular-touch.min.js', 'bower_components/angular-animate/angular-animate.min.js', 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'bower_components/oclazyload/dist/ocLazyLoad.min.js', 'bower_components/angular-ui-router/release/angular-ui-router.min.js', 'bower_components/angular-ui-router/release/stateEvents.min.js', 'bower_components/angular-loading-bar/build/loading-bar.min.js', 'bower_components/angular-ui-select/dist/select.js', 'bower_components/checklist-model/checklist-model.js'],
app_scripts: ['public/angular/scripts/app.js', 'public/angular/scripts/**/*.js'],
app_styles: ['public/angular/styles/reset.css', 'public/angular/styles/layout.css', 'public/angular/styles/components.css', 'public/angular/styles/plugins.css', 'public/angular/styles/themes/green-army.theme.css', 'public/angular/styles/custom.css', 'public/angular/styles/layout/header-loggedin.css', 'public/angular/styles/layout/header-loggedout.css', 'public/angular/styles/pages/sign-in.css', 'public/angular/styles/pages/pos.css', 'public/angular/styles/pages/brand.css', 'public/angular/styles/pages/products.css', 'public/angular/styles/pages/pricing.css', 'public/angular/styles/pages/landing-page.css', 'public/angular/styles/pages/company-profile.css', 'public/angular/styles/invoice-print.css', 'public/angular/styles/angular-custom.css'],
bower_components_styles: ['bower_components/bootstrap/dist/css/bootstrap.min.css', 'bower_components/font-awesome/css/font-awesome.min.css', 'bower_components/animate.css/animate.min.css', 'bower_components/angular-loading-bar/build/loading-bar.min.css', 'bower_components/angular-ui-select/dist/select.min.css', 'bower_components/angular-ui-select/dist/select.css', 'bower_components/angular-bootstrap/ui-bootstrap-csp.css']
};
gulp.task('clean', function () {
return del.sync([paths.dist]);
});
gulp.task('html', ['mainHtml', 'partialsHtml', 'viewsHtml'], function() {
console.log('copying html files started');
});
gulp.task('mainHtml', function() {
gulp.src(paths.html.entry)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(rename('index.html'))
.pipe(gulp.dest(paths.dist));
});
gulp.task('partialsHtml', function() {
gulp.src(paths.html.partials)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/partials'));
});
gulp.task('viewsHtml', function() {
gulp.src(paths.html.views)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/views'));
});
gulp.task('styles', ['bower-styles', 'app-styles'], function(){
console.log('starting styles task');
})
gulp.task('bower-styles', function(){
return gulp.src(paths.bower_components_styles)
.pipe(autoprefixer())
.pipe(concat('bower_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('fonts', function() {
return gulp.src(['bower_components/font-awesome/fonts/fontawesome-webfont.*'])
.pipe(gulp.dest('public/dist/fonts/'));
});
gulp.task('app-styles', function(){
return gulp.src(paths.app_styles)
.pipe(autoprefixer())
.pipe(concat('app_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('scripts', ['bower_scripts','app_scripts'], function(){
console.log('starting scripts task');
})
gulp.task('bower_scripts', function(){
console.log('starting bower scripts task');
return gulp.src(paths.bower_components)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('bower_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('app_scripts', function(){
console.log('starting app scripts task');
return gulp.src(paths.app_scripts)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('app_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('default', ['clean', 'html', 'styles', 'fonts', 'scripts'], function(){
console.log('starting default task');
})
This is the output generated for the particular controller
"use strict";angular.module("sbApp").controller("BrandsCtrl",["$scope","$rootScope","$state","CustomStorage","Brands","$uibModalStack",function($scope,$rootScope,$state,CustomStorage,Brands,$uibModalStack){$scope.vm={brand:{title:"",description:""}},$scope.createBrand=function(){return $scope.vm.errorMsg="",$scope.vm.successMsg="",""==$scope.vm.brand.title||null==$scope.vm.brand.title||void 0==$scope.vm.brand.title||$scope.vm.brand.title.length<3||$scope.vm.brand.title.length>30?$scope.vm.errorMsg="The title must be min 3 max 30 letters":""==$scope.vm.brand.description||null==$scope.vm.brand.description||void 0==$scope.vm.brand.description?$scope.vm.errorMsg="Description is required":$scope.vm.brand.description.length<3||$scope.vm.brand.description.length>1e3?$scope.vm.errorMsg="Description must be min 3 max 1000 letters.":($scope.displaySpinner=!0,void Brands.addNew($scope.vm.brand).then(function(response){$scope.vm.brand.title="",$scope.vm.brand.description="",$scope.vm.successMsg=response.data.title+" added successfully."},function(err){$scope.vm.errorMsg=err.data.message?err.data.message:err.data.msg})["finally"](function(){$scope.displaySpinner=!1}))},$scope.disposeModal=function(){$uibModalStack.dismissAll()}}]);
I am getting error for ui.bootstrap modules, angular.min.js:123
Error:
[$injector:unpr]
http://errors.angularjs.org/1.6.4/$injector/unpr?p0=%24uibModalStackProvider%20%3C-%20%24uibModalStack%20%3C-%20InvoiceCtrl%20%3C-%20BrandsCtrl
I have already used gulp-ng-annotate,.pipe(uglify({mangle:false})) in mu gulpfile.js. Please suggest where it is breaking my app for $uibModal and why?
angular version - AngularJS v1.6.4
Node
It seems that you should add dependency on ui.bootstrap module:
angular.module("sbApp", ["ui.bootstrap"])...
It was duplicate files present and concat was actually adding same file twice
I am using Babel 6 for es2015 and react I have added the presets property in .babelrc but while running gulp in my project I am getting the following error.
ReferenceError: [BABEL] C:\sunny\ubuntushare\projects\viewpoint_ui\src\javascript\app-nyi.jsx: Unknown option: C:\sunny\ubuntushare\projects\viewpoint_ui\.babelrc.presets while parsing file: C:\sunny\ubuntushare\projects\viewpoint_ui\src\javascript\app-nyi.jsx
at Logger.error (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\logger.js:58:11)
at OptionManager.mergeOptions (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:126:29)
at OptionManager.addConfig (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:107:10)
at OptionManager.findConfigs (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:168:35)
at OptionManager.init (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:229:12)
at File.initOptions (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\index.js:147:75)
at new File (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\index.js:137:22)
at Pipeline.transform (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\pipeline.js:164:16)
at Babelify._flush (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\index.js:28:24)
at Babelify.<anonymous> (_stream_transform.js:118:12)
My .babelrc file is
{
"presets": ["react","stage-0","es2015"]
}
If I run babel src -d lib command, it works. But if I run gulp build for building the error appears.
The gulpfile is as follows
'use strict';
var _ = require('lodash');
var gulp = require('gulp');
var webserver = require('gulp-webserver');
var browserify = require('browserify');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');
var sass = require('gulp-sass');
var swig = require('gulp-swig');
var rename = require("gulp-rename");
var nodeResolve = require('resolve');
var source = require('vinyl-source-stream');
var del = require('del');
var buffer = require('gulp-buffer');
var concat = require('concat-stream');
var file = require('gulp-file');
var eslint = require('gulp-eslint');
var concatCss = require('gulp-concat-css');
var production = (process.env.NODE_ENV === 'production');
function getNPMPackageIds() {
// read package.json and get dependencies' package ids
var packageManifest = {};
try {
packageManifest = require('./package.json');
} catch (e) {
// does not have a package.json manifest
}
return _.keys(packageManifest.dependencies) || [];
}
gulp.task('lint', function () {
return gulp.src(['./src/javascript/components/**/*.jsx','./src/javascript/actions/*.jsx','./src/javascript/stores/*.jsx','./src/javascript/utilities/*.js'])
// eslint() attaches the lint output to the eslint property
// of the file object so it can be used by other modules.
.pipe(eslint())
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failOnError last.
//.pipe(eslint.failOnError());
});
gulp.task('templates', ['clean'], function () {
gulp.src('./src/htdocs/**/*.html')
.pipe(swig())
.pipe(gulp.dest('./build/'));
});
gulp.task('server', function () {
gulp.src('./build')
.pipe(webserver({
host: '0.0.0.0',
port: 8080,
// fallback: 'index.html',
livereload: true,
proxies: [{
source: '/ui',
target: 'http://localhost:8080/'
}]
}));
});
gulp.task('sass', ['clean'], function () {
var css = gulp.src('./src/sass/**/*.scss')
.pipe(sass().on('error', sass.logError));
if (production) { css = css.pipe(minify()); }
css.pipe(gulp.dest('./build/css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./src/sass/**/*.scss', ['sass']);
});
// main build task
gulp.task('build', ['build-vendor', 'build-app', 'uikit', 'sass', 'templates', 'copyfiles']);
gulp.task('build-vendor', function () {
var b = browserify({
// generate source maps in non-production environment
debug: !production
});
// do the similar thing, but for npm-managed modules.
// resolve path using 'resolve' module
getNPMPackageIds().forEach(function (id) {
b.require(nodeResolve.sync(id), { expose: id });
});
var stream = b.bundle().pipe(source('vendor.js'))
.pipe(buffer())
.pipe(gulp.dest('./build'));
if (production) {
stream = stream.pipe(uglify())
.pipe(gulp.dest('./build'));
}
return stream;
});
function write(name) {
return concat(function (content) {
// create new vinyl file from content and use the basename of the
// filepath in scope as its basename.
var f = file(name, content, { src: true });
// uglify content
if (production) {
f = f.pipe(uglify());
}
// write content to build directory
f.pipe(gulp.dest('./'));
return f;
});
}
gulp.task('build-app', function () {
var files = ['src/javascript/app.jsx', 'src/javascript/app-2f.jsx', 'src/javascript/app-nyi.jsx'];
var b = browserify(files, {
extensions: ['.jsx'],
debug: !production
});
// exclude all NPM modules
getNPMPackageIds().forEach(function (id) {
b.external(id);
});
b.plugin('factor-bundle', {
outputs: [
write('build/app.js'),
write('build/app-2f.js'),
write('build/app-nyi.js')
]
});
var stream = b.transform(babelify, {presets: ["react","stage-0","es2015"]}).bundle()
.pipe(source('common.js'))
.pipe(buffer())
.pipe(gulp.dest('./build/'));
if (production) {
stream = stream.pipe(uglify())
.pipe(gulp.dest('./build'));
}
return stream;
});
gulp.task('clean', function (cb) {
del([
'build/**/*.*'
], cb);
});
gulp.task('uikit', ['clean'], function () {
gulp.src([(production ? './node_modules/': '../') + 'osstools_uikit/assets/css/screen.css', './node_modules/react-widgets/dist/css/react-widgets.css', './node_modules/rc-slider/assets/index.css', './node_modules/react-bootstrap-table/css/react-bootstrap-table-all.css'])
.pipe(concatCss('osstools_uikit.css', {rebaseUrls:false}))
.pipe(gulp.dest('./build/css'));
});
gulp.task('copyfiles', ['clean'], function () {
gulp.src((production ? './node_modules/' : '../') + 'osstools_uikit/assets/images/**/*')
.pipe(gulp.dest('./build/css/images/'));
gulp.src(['./node_modules/react-widgets/dist/fonts/*', (production ? './node_modules/' : '../') + 'osstools_uikit/assets/fonts/**/*'])
.pipe(gulp.dest('./build/fonts/'));
});
gulp.task('watch', ['build-vendor', 'build-app', 'uikit', 'sass', 'templates', 'copyfiles'], function () {
gulp.watch('./src/javascript/components/**/*.jsx', ['build']);
gulp.watch('./src/javascript/stores/*.jsx', ['build']);
gulp.watch('./src/javascript/actions/*.jsx', ['build']);
gulp.watch('./src/javascript/utilities/*.js', ['build']);
gulp.watch('./src/sass/**/*.scss', ['sass']);
gulp.watch('./src/htdocs/**/*.html', ['templates']);
});
gulp.task('default', ['build', 'server', 'watch']);