I have read all the answers on the internet that I could find on this subject in last two days. Now I am just searching for gulp plugin that can merge broken js files into one big js file and not to throw error in terminal caused by unclosed function in one js file.
Explanation:
I have created js app built with modules.
At the very beginning I didn't knew that this will become big app and therefore I have wrote js code in one file.
Now I have come to an idea to split app.js file like this:
app-start.js (Named IIFE function open)
module1.js
module2.js
etc.
app-end.js (Named IIFE function closed)
I am using gulp as task runner and gulp-concat which works perfectly.
Problem is that when I try to break IIFE function in two files (app-start.js, app-end.js) then gulp doesn't wanna build bundle.js file.
I get error in terminal that I should repair my js code in
app-start.js
So, my question is,
do You maybe know about gulp plugin that will merge multiple js files in given order and never mind the js code errors in those files?
This is my gulp.js code:
var gulp = require('gulp'),
sass = require('gulp-sass'),
uglify = require('gulp-uglify'),
plumber = require('gulp-plumber'),
concat = require('gulp-concat'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create(),
sourceMap = require('gulp-sourcemaps'),
babel = require('gulp-babel');
gulp.task('sass', function() {
gulp.src('resources/sass/config-normalize.sass')
//.pipe(sourceMap.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoprefixer({browsers: ['last 30 versions']}))
.pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
//.pipe(sourceMap.write('.'))
.pipe(gulp.dest('configurator/css'));
gulp.src('resources/sass/config-style.sass')
//.pipe(sourceMap.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoprefixer({browsers: ['last 30 versions']}))
.pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
//.pipe(sourceMap.write('.'))
.pipe(gulp.dest('configurator/css'))
.pipe(browserSync.stream());
});
gulp.task('scripts', function() {
gulp.src([
//'resources/js/vendor/jquery.js',
//'resources/js/vendor/library/neki_file.js',
'resources/js/001-app-start.js',
'resources/js/002-ajax.js',
'resources/js/003-global-variables.js',
'resources/js/050-main.js',
'resources/js/100-my-modules.js',
'resources/js/app-end.js'
])
//.pipe(plumber())
.pipe(babel({
presets: ['es2015']
}))
.pipe(concat('all.js'))
//.pipe(uglify())
.pipe(gulp.dest('configurator/js'))
.pipe(browserSync.stream());
});
gulp.task('php', function() {
gulp.src('./**/*.php')
.pipe(browserSync.stream());
});
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "localhost" //Upisi path do projekta na local hostu bez http://
});
});
gulp.task('images', function() {
return gulp.src('assets/images-uncompressed/**/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('build/images'));
});
gulp.task('watch', function() {
gulp.watch('./**/*.php', ['php']);
gulp.watch('resources/sass/**', ['sass']);
gulp.watch('resources/js/**', ['scripts']);
//gulp.watch('resources/images-uncompressed/*', ['images']);
});
gulp.task('default', ['sass', 'scripts', 'php', 'browser-sync', 'watch']);
The problem is with the order you run your Gulp tasks:
babel parses and transforms JavaScript so it needs well-formed input.
concat doesn't need to understand JavaScript; it just combines text files. It will happily deal with your broken-up files.
If you move concat before babel, Babel can work on a single, well-formed blob of JavaScript built up from your split files.
Related
I created a project with gulp js, installed bootstrap, browse-sync and sass.
My gulpfile.js file looks like this:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
const sass = require('gulp-sass')(require('sass'));
gulp.task('sass', () => {
return gulp.src("./sass/*.scss")
.pipe(sass())
.pipe(gulp.dest("dist/"))
.pipe(browserSync.stream());
});
gulp.task('start', gulp.series('sass', function() {
browserSync.init({
server: "./"
});
gulp.watch("sass/*.scss", gulp.series('sass'));
gulp.watch("./*.html").on('change', browserSync.reload);
}));
gulp.task('default', gulp.series('start'));
When I use the Ctrl + S command in HTML and SCSS files, my project is saved and browser is reloaded; but I want to do this also for my JS files. Can you help me?
Very similar to the way you are dealing with your css, but you can use other plugins like terser to compress your javascript. Here is my js function which concatenates and minifies my javascript before reloading via browsersync
const concat = require('gulp-concat');
const terser = require('gulp-terser');
function js() {
return src(['./js/*.js'])
.pipe(concat('scripts.min.js'))
.pipe(terser())
.pipe(dest('js'))
.pipe(browsersync.stream());
}
I have this gulp code that works fine with browser-sync and the gulp sass compiler, I've tried to insert a browserify task but seems doesn't work, it works if I type on the command line:
browserify src/js/main.js -o src/js/bundle/bundle.js
this is my project structure:
|-project
|--/src
|---/css
|----style.css
|---/js
|----main.js
|----/bundle
|-----bundle.js
|---/scss
|----_bootstrap.scss
|----style.scss
|---/assets
|----/img
|---index.html
|--gulpfile.js
|--package.json
and this is my gulp file:
const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const browserify = require('browserify');
gulp.task('sass', () => {
return gulp.src("./src/scss/*.scss")
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest("./src/css"))
.pipe(browserSync.stream());
});
gulp.task('js',()=>{
return gulp.src('./src/js/main.js')
.pipe(browserify())
.pipe(gulp.dest('./src/js/bundle'))
});
gulp.task('serve', ()=> {
browserSync.init({
injectChanges: true,
server: "./src"
});
gulp.watch("./src/scss/*.scss", gulp.series('sass'));
gulp.watch("./src/js/*.js", gulp.series('js'));
gulp.watch("./src/*.html").on('change', browserSync.reload);
});
gulp.task('default', gulp.series('serve','sass','js'));
I have recently added the 'js' task but when I type gulp in the command line everything works fine except for the browserify task.
as a test the main.js file looks like this:
const jquery = require('../../node_modules/jquery')
console.log(jquery)
and I still get the error 'required is not defined'. there is something i missed out. Many thanks
ok, finally works (seems...) it was not a problem with browserify but with the new version of gulp, instead of:
gulp.task('default', gulp.series('serve','sass','js'));
I have had to do:
gulp.task('default', gulp.parallel('serve','sass','js'));
before the sass and js task didn't start, now with parallel function seems works
I want to use Gulp in my future projects, but what it is more important to me is to add Three.js modular functionality, to the project, with normal plugins example uglify i dont have any problems, but when i run my gulp file in my js code theres always a error THREE is not defined, or if i type
var THREE = require('three');
it says require is not defined, the same if i add a import,
import * as THREE from "three";
import is not defined
hope i had expressed my problem correctly.
This is my Gulpfile.-
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var THREE = require('three');
gulp.task('build', () =>
gulp.src('app.js')
.pipe(bro({
transform: [
babelify.configure({ presets: ['es2015'] }),
[ 'uglifyify', { global: true } ]
]
})
.pipe(gulp.dest('dist')
)))
gulp.watch('*.js', ['build'])
// Lint Task
gulp.task('lint', function() {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Compile Our Sass
gulp.task('sass', function() {
return gulp.src('scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'));
});
// Concatenate & Minify JS
gulp.task('scripts', function() {
return gulp.src('js/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
// Watch Files For Changes
gulp.task('watch', function() {
gulp.watch('js/*.js', ['lint', 'scripts']);
gulp.watch('scss/*.scss', ['sass']);
});
// Default Task
gulp.task('default', ['lint', 'sass', 'scripts', 'watch', 'build']);
EDIT: Think i got it, the documentation of a site was not complete, and i didnt knew i had to install Browserify also with gulp-bro, that seems to be the same, anyway that fixed the require problem. (bringing other new ones) Thank you for everything, and hope this helps somebody.
EDIT2: Now i have found out that Rollup.js is a better solution, with Babel, theres Rollup npm s for that, good luck.
Thank you.
i am currently learning about gulp.js.
as i saw the tutorial and documentation of gulp.js, this code:
gulp.src('js/*.js')
.pipe(uglify())
.pipe(gulp.dest('minjs'));
makes the uglified javascript file with create new directory named 'minjs'. of course, i installed gulp-uglity with --dev-save option. there is no error message on the console so i don't know what is the problem. i tried gulp with "sudo", but still not working.
so i went to the root directory and searched all filesystem but there is no file named 'minjs' so i guess it just not working. why this is happening? anyone knows this problem, it would be nice why this is happening.
whole source code:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
gulp.task('default', function() {
console.log('mifying scripts...');
gulp.src('js/*.js')
.pipe(uglify())
.pipe(gulp.dest('minjs'));
});
I had the same problem; you have to return the task inside the function:
gulp.task('default', function() {
return gulp.src("js/*.js")
.pipe(uglify())
.pipe(gulp.dest('minjs'));
Also, minjs will not be a file, but a folder, where all your minified files are going to be saved.
Finally, if you want to minify only 1 file, you can specify it directly, the same with the location of the destination.
For example:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('browserify', function() {
return browserify('./src/client/app.js')
.bundle()
// Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./public/'));
});
gulp.task('build', ['browserify'], function() {
return gulp.src("./public/main.js")
.pipe(uglify())
.pipe(gulp.dest('./public/'));
});
Hope it helps!
Finally I resolved the question like this:
It was a directory mistake so the gulp task hasn't matched any files; then it couldn't create the dest directory (because no files in output).
const paths = {
dest: {
lib: './lib',
esm: './esm',
dist: './dist',
},
styles: 'src/components/**/*.less',
scripts: ['src/components/**/*.{ts,tsx}', '!src/components/**/demo/*.{ts,tsx}'],
};
At first my scripts was ['components/**/*.{ts,tsx}', '!components/**/demo/*.{ts,tsx}']
And that hasn't matched any files.
I receive custom js and css script as a string through html form. This strings are then saved in files on filesystem. The question is how to minify those files every time they are generated/updated. I am using gulp and laravel elixir.
My first idea was to call exec("gulp something") but not sure how to configure gulp.
Requirments:
gulp-newer
minifyCss
gulp-uglify
First step:(install plugins)
minifyCss and gulp-uglify are used by laravel-elixir. You have to install gulp-newer by npm install gulp-newer --save-dev.
Second step:(define task)
You need to define different tasks for css and js.
CSS task
gulp.task('cssTask', function() {
return gulp.src(cssSrc)
.pipe(newer(cssDest))//compares the css source and css destination(css files)
.pipe(minifyCss())//minify css
.pipe(gulp.dest(cssDest));//save minified css in destination directory
});
Js task
gulp.task('jsTask', function() {
return gulp.src(jsSrc)
.pipe(newer(jsDest))//compares the js source and js destination(js files)
.pipe(uglify())//minify js
.pipe(gulp.dest(jsDest));//save minified js in destination directory
});
Third step:(define custom watch)
You should have a watch task which watches your source directories(cssSrc and jsSrc) and calls its related task.
gulp.task('custom', function() {//Watch task
gulp.watch(cssSrc, ['cssTask']);//watch your css source and call css task
gulp.watch(jsSrc, ['jsTask']);//watch your js source and call js task
});
Fourth step:(run custom watch)
Finally, you must run the custom task by gulp custom.
Conclusion:
Every time, when file is added to the source directory. Gulp will minify the file and store it in destination directory. This is tested locally and it works perfectly.
Completed Gulp file
var gulp = require('gulp');
var elixir = require('laravel-elixir');
var newer = require('gulp-newer');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
cssSrc = 'cssSrc/*.css';//Your css source directory
cssDest = 'cssDest';//Your css destination directory
jsSrc = 'jsSrc/*.js';//Your js source directory
jsDest = 'jsDest';//Your js destination directory
gulp.task('cssTask', function() {
return gulp.src(cssSrc)
.pipe(newer(cssDest))//compares the css source and css destination(css files)
.pipe(minifyCss())//minify css
.pipe(gulp.dest(cssDest));//save minified css in destination directory
});
gulp.task('jsTask', function() {
return gulp.src(jsSrc)
.pipe(newer(jsDest))//compares the js source and js destination(js files)
.pipe(uglify())//minify js
.pipe(gulp.dest(jsDest));//save minified js in destination directory
});
gulp.task('custom', function() {//Watch task
gulp.watch(cssSrc, ['cssTask']);//watch your css source and call css task
gulp.watch(jsSrc, ['jsTask']);//watch your js source and call js task
});
Edited after comment:
I would like something like this: gulp custom srcFile destFile.
For that situation, you need to install new plugin which is called yargs.
Installation:
You can install yargs by npm install yargs --save-dev and then you have to pass source directory and destination directory when custom task is called.
gulp custom --cssSrc=cssSource --cssDest=cssDestination --jsSrc=jsSource --jsDest=jsDestination
For example:
gulp custom --cssSrc=cssSrc/*.css --cssDest=cssDest --jsSrc=jsSrc/*.js --jsDest=jsDest
The completed Gulp file:
var gulp = require('gulp');
var elixir = require('laravel-elixir');
var newer = require('gulp-newer');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var argv = require('yargs').argv;
cssSrc = argv.cssSrc;
cssDest = argv.cssDest;
jsSrc = argv.jsSrc;
jsDest = argv.jsDest;
gulp.task('cssTask', function() {
return gulp.src(cssSrc)
.pipe(newer(cssDest))
.pipe(minifyCss())
.pipe(gulp.dest(cssDest));
});
gulp.task('jsTask', function() {
return gulp.src(jsSrc)
.pipe(newer(jsDest))
.pipe(uglify())
.pipe(gulp.dest(jsDest));
});
gulp.task('custom', function() {
gulp.watch(cssSrc, ['cssTask']);
gulp.watch(jsSrc, ['jsTask']);
});
Note: Every time, the source directory or destination directory is changed, gulp task must be called again.
Use the below gulp modules.
https://www.npmjs.com/package/gulp-minify-css - Minify all your css files.
https://www.npmjs.com/package/gulp-concat-css - Merge all your css in to one file.
https://www.npmjs.com/package/gulp-uglify - Minigy all your JS files.
https://www.npmjs.com/package/gulp-sass - SASS
Refer this answer:
Gulp minify multiple js files to one
Below is sample Gulp File Snippet.
var gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
clean = require('gulp-clean'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
livereload = require('gulp-livereload'),
lr = require('tiny-lr'),
server = lr();
// Clean
gulp.task('clean', function() {
return gulp.src(['css', 'js', 'img'], {
read: false
})
.pipe(clean());
});
gulp.task('styles', function() {
return gulp.src('sass/styles.scss')
.pipe(sass({
style: 'expanded'
}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(gulp.dest('css'))
.pipe(notify({
message: 'Styles task complete'
}));
});
// Concatenate & Minify JS
gulp.task('scripts', function() {
return gulp.src('js/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
// Watch
gulp.task('watch', function() {
// Watch .scss files
gulp.watch('sass/**/*.scss', ['styles']);
// Watch .js files
gulp.watch('js/**/*.js', ['scripts']);
// Watch image files
gulp.watch('img/**/*', ['images']);
// Create LiveReload server
var server = livereload();
// Watch any files in dist/, reload on change
gulp.watch(['sass/**', 'js/**', 'img/**', '*.html']).on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('default', ['styles', 'scripts', 'watch']);
At first place, you need to store the content in a new file. A good place for this is resources/assets/js:
$jsContent = $request->get('js_custom_content');
file_put_contents(base_path('resources/assets/js/custom.js'), $jsContent);
Ok, once created the javascript file, you need to tell to elixir to minify the custom script:
// it will look for resources/assets/js/custom.js
// and it will compress the output to public/assets/js/custom.min.js
mix.scripts(['custom.js'], 'public/assets/js/custom.min.js');
Optionally, you can version it. That means that everytime the script's content change, gulp will generate a new version in order to avoid browser's cache issues:
mix.version(['public/assets/js/custom.min.js']);
Finally, load the script in your view:
<script type="text/javascript" src="{{ url('assets/js/custom.min.js')) }}"></script>
Or with version:
<script type="text/javascript" src="{{ url(elixir('assets/js/custom.min.js')) }}"></script>