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
Related
I've written a gulp task to rename files so that they can be versioned. The problem is that the filenames of the files that the index.html scripts reference are not changed.
For example, in my index.html:
<script src=pub/main_v1.js"></script>
But if you actually navigate through the build folder to the subdirectory pub, you will find main.js.
Here is the custom gulp task:
const gulpConcat = require('gulp-concat');
const gulpReplace = require('gulp-replace');
const version = require('./package.json').version;
gulp.task('version', function () {
var vsn = '_' + version + '.js';
gulp.src('scripts/**/*.js')
.pipe(gulpConcat(vsn))
.pipe(gulp.dest('./prodBuild'));
return gulp.src('./prodBuild/index.html', { base: './prodBuild' })
.pipe(gulpReplace(/* some regex */, /* append vsn */))
.pipe(gulp.dest('./prodBuild'));
});
What do I need to fix/add so that the original filename changes to match that in the script tag?
Note: According to the gulp-concat docs, I should be able to find the concated files at prodBuild/[vsn], where [vsn] is _v1.js. However, it is no where to be found.
Update: The files rename properly in index.html, but I can't seem to get the renaming of the original files to work. Here's a snapshot of my build directory:
prodBuild/
pub/
main.js
someDir/
subDirA/
// unimportant stuff
subDirB/
file2.js
file3.js
// ...other files and folders...
EDIT:
The issue is that you return only one of the two tasks. The first task is simply ignored by gulp, since it is not returned. A simple solutions: Split it into two tasks, and reference the one from the other, like in this SO answer.
Old Answer
This looks like a perfect case for the gulp-rename. You could simply pipe your scripts through gulp-rename, like this:
.pipe(rename(function (path) {
path.basename += vsn;
path.extname = ".js"
}))
Gulp concat is, AFAIK, made for the concatination of files, not particularly for the renaming of them.
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
});
So I have a simple use case, and it seems very similar to the usecase described in the readme for https://github.com/jonkemp/gulp-useref.
I'm trying to generate a templates.js file with all of the Angular templates during the build. I am trying to do this and NOT have a templates.js file in my local project. So the idea was to merge the output of the template stream into the useref stream so that the resulting scripts.js file would contain all of the files indicated in my index file AND the generated templates ouput.
Here's what I have in the gulp task:
gulp.task('usemin:dist', ['clean:dist'], function() {
var templatesStream = gulp.src([
'./app/**/*.html',
'!./app/index.html',
'!./app/404.html'
]).pipe(templateCache({
module: 'myCoolApp'
}));
var assets = $useref.assets({
additionalStreams: [templatesStream]
});
return gulp.src('./app/index.html')
.pipe(assets)
.pipe(assets.restore())
.pipe($useref())
.pipe(gulp.dest('./dist/'));
});
Now this should allow me to merge the output of the templatesStream and turn it all into one scripts.js file, I think...
I've also tried having <script src="scripts/templates.js"></script> of many forms sitting in my index file to try and assist it. None seem to work.
Anyone else doing this same type of thing? Seems like a common use-case.
I was able to get this to work by looking closely at the test cases.
I now have a templates.js script tag on my index.html file which will 404 while in my local environment.
My gulp task looks like this:
gulp.task('useref:dist', ['clean:dist'], function() {
var templateStream = gulp.src([
'./app/**/*.html',
'!./app/index.html',
'!./app/404.html'
]).pipe(templateCache({
module: 'digitalWorkspaceApp'
}));
var assets = $useref.assets({
additionalStreams: [templateStream]
});
var jsFilter = $filter('**/*.js', {restore: true});
return gulp.src('./app/index.html')
.pipe(assets)
.pipe($useref())
.pipe(gulp.dest('./dist/'));
});
Immediately I can't really see the difference, but it may have all hinged on the addition of this non-existent file in my index.html.
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.
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.