hi all i am using gulp uglify and concat to minify js code.
However, i would like to have a way to detect any coding error in the original dev js code so that i can check the original code and not only notified after minified.
May I know how can i do it?
Below is my gulp code.
gulp.task('frontend.js', function() {
return gulp.src([paths.dev.js + 'jquery.js', paths.dev.js + 'bootstrap.js', paths.dev.js + 'basic.js'])
.pipe(jsconcat('script.js'))
.pipe(uglify())
.pipe(gulp.dest(paths.assets.js)) // output: script.js
.pipe( notify({message: 'frontend.js converted'}));
});
That's what source maps are for.
var sourcemaps = require('gulp-sourcemaps');
gulp.task('frontend.js', function() {
return gulp.src([paths.dev.js + 'jquery.js', paths.dev.js + 'bootstrap.js', paths.dev.js + 'basic.js'])
.pipe(jsconcat('script.js'))
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.assets.js)) // output: script.js
.pipe( notify({message: 'frontend.js converted'}));
});
It'll append source maps (i.e. mapping each minified line to the original line) to frontend.js.
Now if you're using a modern browser such as Chrome or Firefox you'll see the original code.
Introduction to source maps
How to use source maps in Chrome
Another gulp plugin
Do you mean that you want to be notified about javascript errors before concatenating and minifying your source files or that you want a way for being able to match a runtime error on the minified file with the original source file containing the offending code?
In the latter case mak answer if perfect, otherwise you should pipe, before the jsconcat, a call to gulp-jshint using maybe jshint-stylish as jshint reporter.
Related
I have set up Gulp to ESLint the javascript in my HTML script tags with the following code.
const eslint = require('gulp-eslint');
gulp.task('process-js', () => {
const scripts = processInline();
return gulp.src(['src/*.html'])
.pipe(errorNotifier())
.pipe(scripts.extract('script'))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError())
.pipe(scripts.restore())
.pipe(gulp.dest('dist'))
});
The linter works well, but seems to give me line numbers that does not correspond to my HTML files, but the line numbers of the extracted javascript from the script tags, which I never see.
How do I get the line numbers of the HTML file? Or can I lint my HTML script javascript in a better way?
I know this question is almost 2 years old, but I also ran into this problem.
This is my solution:
I use gulp-html-extract to extra the script tags contents from the files.
https://github.com/FormidableLabs/gulp-html-extract
I then set pad to true.
For example:
var gulp = require('gulp');
var extract = require("gulp-html-extract");
var eslint = require('gulp-eslint');
gulp.task("eslint:html", function () {
return gulp
.src("templates/**/*.tpl")
.pipe(extract({
sel: "script, code.javascript",
pad: true,
}))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
I hope it's helpful.
You can use Atom, It has eslint plugin.
http://oceanpad.github.io/2016/08/22/2016-08/To-Introduce-ESLint-to-Atom/
It behave very well.
This seems like a very simple question, but spent the last 3 hours researching it, discovering it can be slow on every save on a new file if not using watchify.
This is my directory tree:
gulpfile.js
package.json
www/
default.htm
<script src="toBundleJsHere/file123.js"></script>
toBundletheseJs/
componentX/
file1.js
componentY/
file2.js
componentZ/
file3.js
toPutBundledJsHere/
file123.js
Requirements.
On every creation or save of a file within the folder toBundleTheseJs/ I want this file to be rebundled into toBundleJsHere/
What do I need to include in my package.json file?
And whats the minimum I need to write into my gulp file?
This should be as fast as possible so think I should be using browserify and watchify. I want to understand the minimum steps so using package manager like jspm is overkill a this point.
thanks
First you should listen to changes in the desired dir:
watch(['toBundletheseJs/**/*.js'], function () {
gulp.run('bundle-js');
});
Then the bundle-js task should bundle your files. A recommended way is gulp-concat:
var concat = require('gulp-concat');
var gulp = require('gulp');
gulp.task('bundle-js', function() {
return gulp.src('toBundletheseJs/**/*.js')
.pipe(concat('file123.js'))
.pipe(gulp.dest('./toPutBundledJsHere/'));
});
The right answer is: there is no legit need for concatenating JS files using gulp. Therefore you should never do that.
Instead, look into proper JS bundlers that will properly concatenate your files organizing them according to some established format, like commonsjs, amd, umd, etc.
Here's a list of more appropriate tools:
Webpack
Rollup
Parcel
Note that my answer is around end of 2020, so if you're reading this in a somewhat distant future keep in mind the javascript community travels fast so that new and better tools may be around.
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('js', function (done) {
// array of all the js paths you want to bundle.
var scriptSources = ['./node_modules/idb/lib/idb.js', 'js/**/*.js'];
gulp.src(scriptSources)
// name of the new file all your js files are to be bundled to.
.pipe(concat('all.js'))
// the destination where the new bundled file is going to be saved to.
.pipe(gulp.dest('dist/js'));
done();
});
Use this code to bundle several files into one.
gulp.task('scripts', function() {
return gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js']) //files separated by comma
.pipe(concat('script.js')) //resultant file name
.pipe(gulp.dest('./dist/')); //Destination where file to be exported
});
I have the following gulp task for bundling javascript:
gulp.task('js', function () {
return gulp.src(paths.js)
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(concat('bundle.min.js'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
When I run this in the Chrome dev tools, sourcemaps are found and breakpoints work, but variables can't be debugged.
Take this example chunk of angular code:
iarApp.config(['$animateProvider', function ($animateProvider) {
$animateProvider.classNameFilter(/angular-animate/);
}]);
If I add a breakpoint to see the value of $animateProvider, I get the following:
But if I turn off variable mangling in Uglify:
.pipe(uglify({ mangle: false }))
Then it works:
So it seems that the gulp-sourcemaps plugin can't follow up variables after Uglify mangles the names.
Can anyone else get the same issue and/or know a solution?
Turns out this is just not possible currently, since this is not part of the specification for source maps.
There are some proposals to add this feature, so we will have to wait until the spec and implementations are updated.
In my gulpfile.js, I'm trying to minify and enable sourcemaps in a release task.
Based on a config variable, I'm trying to pipe further actions into the stream. The check for the condition is using gulp-if-else. My set of dependencies (only relevant ones) are below
var gulp = require('gulp');
var browserify = require('browserify');
//... elided
var through= require('through2');
var sourcemaps= require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var ifelse = require('gulp-if-else');
Here's the code that I'm having trouble with. If I keep three ifelse pipe calls individually (currently commented out), then the source is uglified and sourcemap is created as expected.
Repeating the condition didn't feel clean - so I tried replacing it with the minify function - and then the behavior is strange.
If I don't give relative path in sourcemaps.write then the js file has a inline sourcemap.
With a relative path, source is uglified, the js has a sourcemap comment pointing to app.js.map but app.js.map itself is never generated
var minify = function() {
var stream = through({objectMode:true})
stream
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write("./"));
return stream;
};
var bundledStream = through({objectMode:true});
bundledStream
// Report compile errors
.on('error', handleErrors)
.on('end', reportFinished)
// Use vinyl-source-stream to make the
// stream gulp compatible. Specifiy the
// desired output filename here.
.pipe(source(entry + '.js'))
// Specify the output destination
.pipe(buffer())
// uncommenting the following three lines works
//.pipe(ifelse(!config.debug,function() {return sourcemaps.init()}))
//.pipe(ifelse(!config.debug, uglify))
//.pipe(ifelse(!config.debug,function() {return sourcemaps.write("./")}))
// this works partially?!? but I don't know why. I'd like this version to work
.pipe(ifelse(!config.debug, minify))
.pipe(gulp.dest(config.destFolder));
I'm just picking up gulp (and node, really) and ran into this weird behavior that I can't seem to reason about. Would be a great help if someone can demystify it for me.
UPDATE: Complete gulpfile.js
UPDATE2: Added gulp-filelog. added pipe(filelog("minify")) and pipe(filelog("outer")) to the streams. filelog prints two files inside the fn but only one file outside. Why is the second file being dropped/ignored? What am I missing?
[09:43:24] [minify] [1] [E:\....\Dashboard\app.js.map]
[09:43:24] [minify] [2] [E:\....\app.js]
[09:43:24] [outer] [1] [E:\....\Dashboard\app.js]
[09:43:24] [outer] Found [1] files.
[09:43:24] [minify] Found [2] files.
Once magnification is done, and let's say I had some bug,
and I want the console of browser to point me to original source so I could see the problem clearly instead of minified lines of code.
Script.js + many more files (concatenation plus minification)
var somevar = 4
console.log(someVar) //misspelled var name
console will take me to this file
script.min.js
var somevar=4;console.log(someVar)
I've seen some .map files with some js libraries, don't know how they work.
Can someone advise how can the console of a browser can refer to original source in case of an error /problem in a minified file.
gulp.task("app", function() {
var app = [
"js/libs/abc.js",
"js/file1.js",
"js/file2.js"
];
gulp.src(app)
.pipe(concat("app.min.js"))
.pipe(uglify())
.pipe(gulp.dest("js"))
});
Install this to your dev dependencies
https://www.npmjs.com/package/gulp-sourcemaps
gulp.src(app)
.pipe(concat("app.min.js"))
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest("js"))
Make sure the generated JavaScript file, example.js, has the source mapping url at the end as follows:
//# sourceMappingURL=example.js.map