How can I strip comments from HTML with Gulp.js? - html

I have just started using gulp.js and I want to know if there is a way to strip out comments from my HTML files. Of course, I don't want the comments removed from the original files, just those that will be in production. Say I have a file like this:
index.html // before gulp
<html>
<!-- Some comments -->
<!-- Some more comments -->
<div>
// some stuff
</div>
</html>
index.html // after gulp
<html>
<div>
// some stuff
</div>
</html>
Part of my question is that I'm not really sure how this should work. Am I suppose to put all of my gulped HTML files (with comments removed) in a separate directory, and only push that up to my server? I still want the comments to exist in my HTML files on my testing environment (and on my repo), just not on the files that go out to production. Any help in my understanding of how to do this would be much appreciated!

with gulp-htmlmin you can do it like this:
.pipe(htmlmin(
{
removeComments: true
}
))
see https://github.com/kangax/html-minifier#options-quick-reference for all available options.

I normally use gulp-htmlmin for removing comments among many other optimizations one can do on html files. I have a SRC folder containing the source html files with comments and a BUILD folder that contains all the optimized assets (js, css and html too) and I serve the files from the build folder when in production mode.

With https://www.npmjs.org/package/gulp-preprocess you can remove the comments.
So you would have one folder - as above - for pre gulp files and one for after it.
Then you could make 2 different tasks. One that only copies the html files and one which copies them and removes the comments.

Perhaps the simplest way is with gulp-decomment:
var gulp = require('gulp');
var decomment = require('gulp-decomment');
gulp.task('default', function () {
return gulp.src('input.js')
.pipe(decomment())
.pipe(gulp.dest('dest'));
});

Related

Gulp inject HTML snippets into named targets

we're handling low level html markup as npm modules where one could specify via comment, the name of a modules whose supporting html would be injected at that location. A module contains the html, supporting SCSS and vanilla JS. From a SCSS & JS standpoint everything is buttoned up. The moment the module is installed, the SCSS is compiled, concatenated & appended to a core CSS file and then minified. The JS treatment is very similar.
Where I'm getting very hung up on is how to treat the html snippets. Here is what I've got, which works but this isn't dynamic in any way.
gulp.task('inject-atoms', function () {
gulp.src('./index.html')
.pipe(inject(gulp.src(['./node_modules/my-module-name/my-module-name.html']), {
starttag: '<!-- inject:html -->',
transform: function (filePath, file) {
return file.contents.toString('utf8')
}
}))
.pipe(gulp.dest('./'));
});
What I'd like to be able do (within the target index.html file) is specify module names whose html snippets get injected. So something like:
<!-- inject:my-module-ABC --!>
<!-- inject:my-module-XYC --!>
The only requirement being that the modules have been installed prior to trying to inject their snippets. So the gulp task would need to sweep through the index file and for each inject comment, go fetch that module's html snippet and inject it in.
Any tips on helping me move in the right direction?
Thanks!

Visualizing README.md files in my website

I want to visualize README.md files from a project in github, in my website.
What is the best way to do this? Like fetch the markdown code and process the mark down locally? Or there is a way to fetch the already processed markdown from github?
One possible solution is to use a javascript-based markdown parser, such as https://github.com/evilstreak/markdown-js.
That library can be loaded from the browser and can display the markdown. In this example (taken from the aforementioned site), you would need to fetch and insert the markdown in the output of your site:
<!DOCTYPE html>
<html>
<body>
<textarea id="text-input" oninput="this.editor.update()"
rows="6" cols="60">Insert proxied **Markdown** here.</textarea>
<div id="preview"> </div>
<script src="lib/markdown.js"></script>
<script>
function Editor(input, preview) {
this.update = function () {
preview.innerHTML = markdown.toHTML(input.value);
};
input.editor = this;
this.update();
}
var $ = function (id) { return document.getElementById(id); };
new Editor($("text-input"), $("preview"));
</script>
</body>
</html>
Use Github API - Markdown on your javascript.
Here is a much better way to do it that seems to be more in line with the questions and it certainly suited my needs.
This implements a server-side, back-end processor that servers up HTML rendered from Markdown on the fly.
Here is an excerpt for PHP, but other languages are supported and documented in the link:
PHP
Download PHP Markdown (or PHP Markdown Extra) and PHP SmartyPants
from Michel Fortin.
Put markdown.php and smartypants.php somewhere in
PHP's include path (or in the same directory as render.php).
Add an alias in your Apache config:
Alias /markdown/ "/var/www/support/markdown/"
Add rewrite rules. This can be done in the .htaccess file for a specific folder, or in the global Apache config. Some common extensions are included, but you can adjust them to your needs. (You might want to process all text as Markdown by adding "txt".)
# display Markdown as HTML by default
RewriteEngine on
RewriteRule .+\.(markdown|mdown|md|mkd)$ /markdown/render.php
RewriteRule .+\.(markdown|mdown|md|mkd)\-text$ /markdown/render.php [L]
https://github.com/zhlicen/md.htm
An example of zeromd.js
Just serve the md.htm file and md files, and visit directly by url: /md.htm?src=README.md
Or directly use my github page, Example:
https://b.0-0.plus/blog/md.htm?src=https://raw.githubusercontent.com/microsoft/vscode/main/README.md

How can I use gulp to concatenate bower_components that contain assets?

I'm developing a sample application which uses bower for it's dependency management and gulp for it's build system.
I've used the main-bower-files plugin to copy all of the relevant files from the bower_components directory into a build/dist/bower_components directory.
This all works perfectly, and I can open my application's index.html which properly points to each of these files and they properly point to the assets.
My next step is to concatenate the bower_components so that I have a single CSS and a single JS file along with all of the assets (fonts, images, etc.). I have used gulp-useref to bundle all of the components, and it seems to work nicely.
However, some of the CSS and JS files being combined use relative paths to reference assets which are now incorrect since everything is in a single file:
FontAwesome
Bootstrap
and a custom bower component we are creating
Is there a standard solution for fixing the assets?
Do I need to use gulp to update the asset references or perhaps use a different plugin?
Using gulp-replace plugin we can concatenate bower_components assests.
For example:
var replace = require('gulp-replace');
gulp.task('fix-paths', ['minify'], function() {
gulp.src('public/css/site.css')
.pipe(replace('../', '../bower_components/bootstrap/dist/'))
.pipe(gulp.dest('public/css'));
});
I am using the gulp inject plugin to inject the concatenated file to the html. Something like this -
gulp.task('html', ['styles', 'vendor-js', 'templateCache', 'scripts'], function() {
gulp.src('./*.html')
.pipe(inject(gulp.src(['./dist/js/**/*.js'])
.pipe(angularFilesort()), {
'ignorePath': 'dist/js',
'addRootSlash': false,
'addPrefix': 'scripts'
}))
.pipe(inject(gulp.src(['./dist/vendors/**/*.js', '!./dist/vendors/less/less.js'], {
read: false
}), {
'name': 'vendors',
'ignorePath': 'dist/vendors',
'addRootSlash': false,
'addPrefix': 'vendors'
}))
.pipe(inject(gulp.src(['./dist/css/*.css'], {
read: false
}), {
'ignorePath': 'dist/css',
'addRootSlash': false,
'addPrefix': 'styles'
}))
.pipe(gulp.dest('dist'));
});
Let me know if you need any more code.
For CSS, I would suggest using gulp-rework, which wraps rework that has a number of very helpful plugins.
One of these is url, which provides a function for updating the urls contained within CSS.
An example where this is useful, is in CSS that contains no path to replace; e.g.
url(backgroundimage2.png)
Or, you want to perform different alterations of the URL based on type (e.g. only images, not web fonts).
A function can be composed that tests for asset type; the following example processes only image files:
// CSS
.pipe(cssFilter)
.pipe(rework(reworkUrl(function (url) {
// modifications on url, e.g. using http://medialize.github.io/URI.js/
if (url.match(/[^/]+(jpg|jpeg|png|gif)$/))
{
return '/lib/img/' + url.replace('../', '');
}
else
{
return url;
}
})))
Recently I found same problem so gone through various solutions and one of them was to replace the content of css in this answer itself. After looking the font-awesome.css it was clear that it refers relative path to reach fonts folder. same was the case with bootstrap css. Solution is simple now always make sure to keep css and fonts folder at same level and copy data. Even include your app specific min files here. Single place for all dist files makes life easy

How to configure Gulp task to copy bower resources

What is the right way to copy bower resources using gulp.
I want a task "build" (for dev) that will:
Transforme /src/index.jade to /build/index.html
Copy bower resources to /build/vendor/*
Copy my resources to /build/css, js, assets
Inject this resources (my and bower's) in index.html
I'm having trouble with "font awesome", because they resources (.ttf, .otf...) are referenced in font-awesome.css as: "../font/fontawesome-webfont.ttf"
I tried with wiredep, that copied js and css to /vendor (no folder structure) and did not copied the fonts.
I also tried with main-bower-files, that also copied all resources (and fonts) to /vendor folder but also with no inner structure
And tried with bowerNormalizer, that create a folder structure like "/vendor/font-awesome//" (invalid too)
And, finally, tried with gulp-bower-files, that copied all bower files (min, dist, src), that is not right also
PS: I don't want min/uglify/concat right now. This things will be done later, at "dist" task
Another approachment:
suposing you have installed:
gulp
run-sequence
main-bower-files
gulp-inject
if you dont, you can install with npm like:
npm install gulp run-sequence main-bower-files gulp-inject --save-dev
Saving your dependencies into html file
Once you have it we start to configure the gulp tasks
//Here we only copy files to folder inside source code.
//In this case ./src/lib/
gulp.task("bower:copyfiles", function(cb){
return gulp.src(mainBowerFiles())
.pipe(gulp.dest('./src/lib'))
cb();
});
//This task is the one wich insert the script tag into
// HTML file. In this case is index.html and is in root
gulp.task('bower:insertfiles', function(cb){
return gulp.src('./src/index.html') //file with tags for injection
.pipe(inject(gulp.src(['./src/lib/*.js', './src/lib/*.css'], {read: false}), {
starttag: '<!-- bower:{{ext}} -->',
endtag: '<!-- endbower -->',
relative:true
}
))
.pipe(gulp.dest('./src')); //where index.html will be saved. Same dir for overwrite old one
})
//And this task will launch the process of copy and include into index.html
gulp.task('bower:buildlib', function(cb) {
runSequence('bower:copyfiles', 'bower:insertfiles',cb);
})
Now we have half process, we need to insert the tags into index.html to let gulp know where has to include the content
<html>
<head>
<meta charset="utf-8">
<title></title>
<!-- bower:css -->
<!-- HERE WILL BE INSERTED THE CODE. -->
<!-- endbower -->
</head>
<body>
<!-- bower:js -->
<!-- HERE WILL BE INSERTED THE CODE. -->
<!-- endbower -->
</body>
</html>
and the last step is run our task in command line
gulp bower:buildlib
Notes:
Is known some libraries installed with bower has different file configuration. f.e.: when you install bootstrap, css files are not included because inside bower.json (in the library folder on bower_components or whatever you have) is set in that way. You can fix this overwriting these options in the bower.json on your project root directory adding it like this (same bootstrap example):
"overrides":{
"bootstrap":{
"main":[
"dist/js/bootstrap.js",
"dist/css/bootstrap.min.css",
"less/bootstrap.less"
]
}
}
this way you set wich files are going to be include and wich ones not.
I solved this problem like this:
gulp.task('move', ['yourDependencies'], function(){
gulp.src(['bower_components/*.js', 'bower_components/somefile'], {
base:'.bower_components/somepath'
})
.pipe(gulp.dest(build/vendor/);
}
the base options defines the base dir of the file (that means it will not create the same dirs in the build folder). For more explanations visit: Why does gulp.src not like being passed an array of complete paths to files?
I do not know how to transform .jade - files into .html files (i'm sorry).
The inject thing can be solved with the gulp-inject plugin:
https://www.npmjs.com/package/gulp-inject
Sorry for my bad english :-)

What is the correct way to express a path in order to get Pelican generated html to link to an image?

I'm just starting to create a blog with Pelican and wanted to link to an image. I did this by including the following line in my Markdown file:
<img src="./myImg1a.png" alt="./myImg.png" style="width: 750px; height: 800px;"/>
This line was successfully reproduced in the html file, which Pelican placed in the output directory (i.e. /myBlog/output). I placed the png files in the output directory (i.e. the same directory as the html files and got the following error:
WARNING:root:Unable to find file /category/myImg1a.png/index.html or variations.
where /category refers to myBlog/output/category. When I, instead, used the following html code:
<img src="/myImg1a.png" alt="/myImg.png" style="width: 750px; height: 800px;"/>
everything worked fine. I don't understand why this should be:
If the image file is in the same directory as the html file, shouldn't "./myImg1.png" be correct and "/myImg.png" be incorrect?
Why was the folder /category/myImg1a.png/index.html being sought at all?
First of all, by design, you should not change the contents of the output directly/manually.
You should put all your static contents in separate directory which is usually named as images or paths. And, then configure the path(s) in pelicanconf.py as:
# ...
PATH = 'content'
STATIC_PATHS = ['images', 'files'] # add any no. of locations
# ...
In that case, when Pelican is building actual page, it will look for any referenced static file in ./content/images and ./content/files locations. If cannot find there, it will emit the error message.
Now, answering to your trouble ...
By,
... src="./myImg1a.png" ...
Pelican look for this myImg1a.png file in your myBlog/content/ folder as you are mentioning ./ which is the root folder for Pelican is working on.
But, when you are referring it as
... src="/myImg1a.png" ...
Pelican eventually finds it in the html file's directory. By getting / as location, Pelican is looking for it in the same directory of your myblog/my-blog-post/index.html which is myblog/my-blog-post/.
Hence, working. But not in the ideal way.
For a deeper understanding, please take a look into Pelican's documentation on this matter.
Why was the folder /category/myImg1a.png/index.html being sought at all?
Pelican, here, just trying to be smart.