linking css,js file across project folders [duplicate] - javascript

This question already has answers here:
What are the new frames? [closed]
(3 answers)
Closed 4 years ago.
I have a vanilla project where I import the basic frameworks I am going to use like js,Bootstrap and others.
I have a index file like so,
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="frameworks/jquery.js"></script>
<script type="text/javascript" src="frameworks/p5.js"></script>
<link href="frameworks/bootstrap/css/bootstrap.css" rel="stylesheet">
<script type="application/javascript" src="frameworks/bootstrap/js/popper.js"></script>
<script type="application/javascript" src="frameworks/bootstrap/js/bootstrap.js"></script>
</head>
<body>
Hello, foo!
</body>
</html>
If I am going to have multiple html files like, bar.html foo.htmlm I would need to link all the files again in that file which is going to be hectic. What is the solutions for this? How can I just import once and use across all .html files?

You need to use a templating engine like Handlebars, EJS or Swig. I would recommend EJS out of those suggestions. These templating engines have a concept called "partials" that you would want to use.
Here is a Stack Overflow question about EJS partials. Essentially, partials allow you to use smaller templates in your templates. So you can create a partial called "header.html" and include it multiple templates like "home.html" or "article.html."

Well I have 2 options for you
1. Use GULP
you can read more about gulp here
In short gulp helps bind different modules into a complete HTML file.
Lets say you have footer.html, header.html which contains header information such as CSS and JS.
There will be gulpfile.js where you define how you want to generate Final HTML code and many other stuffs.
My gulpfile.js looks like this. All steps are self explanatory
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
cleanCSS = require('gulp-clean-css'),
uglify = require('gulp-uglify'),
pump = require('pump'),
rigger = require('gulp-rigger'),
imagemin = require('gulp-imagemin'),
imageminJpegRecompress = require('imagemin-jpeg-recompress'),
imageminSvgo = require('gulp-imagemin').svgo,
imageminPngquant = require('imagemin-pngquant'),
browserSync = require('browser-sync').create(),
watch = require('gulp-watch'),
del = require('del');
var task = {};
var path = {
build: {
html: 'dist/',
stylesheets: 'dist/assets/stylesheets/',
img: 'dist/assets/images/',
javascript: 'dist/assets/javascript/',
fonts: 'dist/assets/fonts/'
},
src: {
html: 'src/*.html',
stylesheets: 'src/assets/stylesheets/*.scss',
img: 'src/assets/images/**/*.*',
javascript: 'src/assets/javascript/**/*.js',
fonts: 'src/assets/fonts/**/*.*'
},
watch: {
html: 'src/**/*.html',
stylesheets: 'src/assets/stylesheets/**/*.scss',
img: 'src/assets/images/**/*.*',
javascript: 'src/assets/javascript/**/*.js',
fonts: 'src/assets/fonts/**/*.*'
}
};
// HTML
gulp.task('html:build', task.html = function () {
gulp.src(path.src.html)
.pipe(rigger())
.pipe(gulp.dest(path.build.html))
.pipe(browserSync.reload({
stream: true
}));
});
//Stylesheets
gulp.task('sass:build', function () {
return gulp.src(path.src.stylesheets)
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest(path.build.stylesheets))
.pipe(browserSync.reload({
stream: true
}));
});
// JAVASCRIPT
gulp.task('javascript:build', task.javascript = function () {
gulp.src(path.src.javascript)
.pipe(uglify())
.pipe(gulp.dest(path.build.javascript))
.pipe(browserSync.reload({
stream: true
}));
});
// FONTS
gulp.task('fonts:build', task.fonts = function () {
gulp.src(path.src.fonts)
.pipe(gulp.dest(path.build.fonts))
.pipe(browserSync.reload({
stream: true
}));
});
//Images
gulp.task('img:build', task.img = function () {
gulp.src(path.src.img)
.pipe(imagemin([
imageminJpegRecompress({quality: 'low'}),
imageminSvgo(),
imageminPngquant({nofs: true, speed: 1})
]))
.pipe(gulp.dest(path.build.img))
.pipe(browserSync.reload({
stream: true
}));
});
// Server
gulp.task('server:build', function() {
browserSync.init({
port : 3200,
server: {
baseDir: "dist",
routes: {
'/node_modules': 'node_modules'
}
},
notify: {
styles: {
top: 'auto',
bottom: '0'
}
},
open: true
});
});
gulp.task('build', [
'html:build',
'sass:build',
'server:build',
'img:build',
'javascript:build',
'fonts:build'
]);
gulp.task('watch', function () {
watch([path.watch.stylesheets], function (event, cb) {
gulp.start('sass:build');
});
watch([path.watch.html], function (event, cb) {
gulp.start('html:build');
});
watch([path.watch.img], function (event, cb) {
gulp.start('img:build');
});
watch([path.watch.javascript], function (event, cb) {
gulp.start('javascript:build');
});
watch([path.watch.fonts], function (event, cb) {
gulp.start('fonts:build');
});
});
gulp.task('default', ['build', 'watch']);
2. Have a main index.html where you load all scripts and css
Have a container where you load your htmls inside that container. In this case your URL will remain static and only content will change.
you don't need to load scrips and css as they are already loaded.
there are some points to note though
you need to maintain a unique id across all files, as id's might clash same goes for css.

Related

How to include partial html file into another html file using gulp?

I have two folders, dist and partials, the 'dist' folder contains the index.html file and the 'partials' folder contains header.html, navbar.html, and footer.html files. I want to include these partial files into index.html. I tried the gulp-file-include plugin, It works fine but I want that whenever I perform any changes into any partial file, The index.html file should be updated. I'm not able to do this with the gulp-file-include plugin, Please any other solution...?
gulpfile.js
'use strict'
const fileinclude = require('gulp-file-include');
const gulp = require('gulp');
gulp.task('fileinclude', function() {
return gulp.src(['dist/index.html'])
.pipe(fileinclude({
prefix: '##',
basepath: '#file'
}))
.pipe(gulp.dest('dist'));
});
index.html
##include('../partials/header.html')
##include('../partials/navbar.html')
##include('../partials/footer.html')
Use gulp.watch(...) to track all changes, it's not just for html. Any files in gulp are tracked using this method.
const gulp = require('gulp');
const include_file = require('gulp-file-include');
gulp.task('include', () => {
return gulp.src('./res/*.html')
.pipe(include({
prefix: "##",
basepath: "#file"
}))
.pipe(gulp.dest('./public'));
});
gulp.task('watch', () => {
gulp.watch('./res/*.html', gulp.series('include'));
})
also my variant:
const { src, dest, watch } = require('gulp'),
include_file = require('gulp-file-include');
function include() {
return src('./res/*.html')
.pipe(file_include({
prefix: '#',
basepath: '#file'
}))
.pipe(dest('./public/'));
}
function watching() {
watch('./res/*.html', include);
}
exports.watch = watching;
then:
gulp watch

Gulp 4 Sass + BrowserSync Injection with MAMP

I've spent the whole day trying to figure this out right. I am aware of
Gulp 4 & BrowserSync: Style Injection?
and tried different approaches to this. What am I missing?
I am trying to get gulp to inject the sass generated style to the browser. As of now, it does open a new tab with the generated css, but it does neither refresh nor inject the newly generated style when changing. I get:
[Browsersync] Watching files...
[21:27:36] Starting 'buildStyles'...
[21:27:36] Finished 'buildStyles' after 40 ms
[Browsersync] File event [change] : site/templates/styles/main.css
But it doesn't inject. Here's my gulpfile.js:
const { src, dest, watch, series, parallel } = require('gulp');
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const paths = {
sass: {
// By using styles/**/*.sass we're telling gulp to check all folders for any sass file
src: "site/templates/styles/scss/*.scss",
// Compiled files will end up in whichever folder it's found in (partials are not compiled)
dest: "site/templates/styles"
},
css: {
src: "site/templates/styles/main.css"
}
};
function buildStyles(){
return src(paths.sass.src)
.pipe(sass())
.on("error", sass.logError)
.pipe(dest(paths.sass.dest))
}
function watchFiles(){
watch(paths.sass.src,{ events: 'all', ignoreInitial: false }, series(buildStyles));
}
function browserSync(done){
browsersync.init({
injectChanges: true,
proxy: "http://client2019.local/",
port: 8000,
host: 'client2019.local',
socket: {
domain: 'localhost:80'
},
files: [
paths.css.src
]
});
done();
// gulp.watch("./**/*.php").on("change", browserSync.reload);
}
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles;
exports.watch = watchFiles;
exports.build = series(buildStyles); // $ gulp build
What am I missing?
I don't know if I fully understand what are you want.
To auto refresh the browser with BrowserSync, after saving your last changes, I'm using this code on my gulp file:
var paths = {
styles: {
src: "./src/styles/scss/**/*.scss",
dest: "./view/styles"
},
htmls: {
src: "./src/**/*.html",
dest: "./view"
}
};
const styles= () => {
return...
}
const html= () => {
return...
}
const watch = () => {
browserSync.init({
server: {
baseDir: "./view"
}
});
gulp.watch(paths.styles.src, style);
gulp.watch(paths.htmls.src, html);
gulp.watch("src/**/*.html").on('change', browserSync.reload);
};
exports.style = style;
exports.html = html;
exports.watch = watch;
var build = gulp.parallel(style, html, watch);
gulp.task('default', working);
Then I just execute gulp for build and watch with auto reload.

Avoid using document.write() occurs when trying to load a dashboard page in Chrome

So I have been stuck on this problem for longer than i'd care to admit but as a Angular newbie I am completely baffled.
So I am following some online tutorials in order to implement Gulp into an application I am working on and whenever I run the Gulp tasks I get an error in Chrome which states:
"[Violation] Avoid using document.write().(anonymous) # (index):13"
and:
//\/script>".replace("HOST",
location.hostname)); //]]>
I am even more confused as the index.html doesn't actually contain a document.write reference before execution. Also despite mostly following a tutorial when integrating Gulp I cannot seem to have the CSS background changes reflected on screen, could this be related to the previously mentioned error?
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>SmartSystemOverviewWeb</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="app/css/styles.css" rel="stylesheet">
</head>
<body>
<sso-dashboard>
Loading...
<i class="fa fa-spinner fa-spin"></i>
</sso-dashboard>
<script type="text/typescript" src="app/vendor.ts"></script>
<!-- <script src="app/app.component.js"></script> -->
</body>
</html>
gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var tsc = require('gulp-typescript');
var tslint = require('gulp-tslint');
var tsProject = tsc.createProject('tsconfig.json');
var config = require('./gulp.config')();
var browserSync = require('browser-sync').create();
var superstatic = require('superstatic');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var minifyCSS = require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
/*
-- TOP LEVEL FUNCTIONS --
gulp.task - Define tasks
gulp.src - point to files to use
gulp.dest - point to folder to output
gulp.watch - watch files + folders for changes
*/
// Logs Message
gulp.task('message', function(){
return console.log('Gulp is running...');
});
gulp.task('ts-lint', function() {
console.log('ts-lint task running...');
return gulp.src(config.allTs)
.pipe(tslint())
.pipe(tslint({
formatter: "verbose"
}))
// .pipe(tslint.report("verbose"))
})
gulp.task('compile-ts', function() {
console.log('compile-ts task running...');
var sourceTsFiles = [
config.allTs,
config.typings
];
var tsResult = gulp
.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsProject())
return tsResult.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.tsOutputPath));
});
gulp.task('sass', function(){
console.log('sass is running...');
// return gulp.src('src/app/styles.scss')
return gulp.src('src/app/**/*.scss')
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('src/app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
console.log('browserSync is running...');
browserSync.init({
// port: 4200,
// file: ['index.html', '**/*.js'],
// injectChanges: true,
// logFileChanges: true,
// logLevel: 'verbose',
// notify: true,
// reloadDelay: 0,
server: {
baseDir: 'src',
middleware: superstatic({debug: false})
},
})
})
gulp.task('watch', ['browserSync', 'sass'], function(){
gulp.watch('src/app/**/*.scss', ['sass']);
gulp.watch('src/app/component/**/*.scss', ['sass']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/app/**/*.html', browserSync.reload);
gulp.watch('src/app/component/**/*.html', browserSync.reload);
gulp.watch('src/app/**/*.js', browserSync.reload);
gulp.watch('src/app/component/**/*.js', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
})
gulp.task('useref', function() {
var assets = useref.assets();
return gulp.src('app/*.html')
.pipe(assets)
.pipe(gulpIf('*.css', minifyCSS()))
.pipe(gulpIf('*.js', uglify()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist'))
});
gulp.task('images', function() {
return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
.pipe(cache(imagemin( {
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
});
gulp.task('fonts', function() {
return gulp.src('app/fonts/**/*')
.pipe(gulp.dest('dist/fonts'))
});
// Cleaning
gulp.task('clean', function(callback) {
del('dist');
return cache.clearAll(callback);
})
gulp.task('clean:dist', function(callback) {
del(['dist/**/*', '!dist/images', '!dist/images/**/*'], callback)
});
// Build Sequences
gulp.task('build', function (callback) {
runSequence('clean:dist',
['sass', 'useref', 'images', 'fonts'],
callback
)
})
gulp.task('default', function (callback) {
runSequence(['message', 'ts-lint', 'sass', 'browserSync', 'watch'],
callback
)
})
styles.css
.testing {
width: 71.42857%; }
.head {
background: red; }
.body {
background: #177794; }
.html {
background: green; }
Any tips or advice to solve these issues would be greatly appreciated!
Thanks in advance!
The violation message is caused by browserSync that will add the following line to the document.
<script id="__bs_script__">//<![CDATA[
document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.23.3'><\/script>".replace("HOST", location.hostname));
//]]></script>
This can be pretty much ignored as it will only affect the app when it's viewed through browserSync and not the final app.
If anyone stumbles across this post. I found a handy solution to get around the warning being displayed by browserSync.
<script id="__bs_script__">//<![CDATA[
let script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('src', '%script%'.replace("HOST", location.hostname));
document.body.appendChild(script);
//]]></script>
Taken from this post.
Happy coding =)

Gulp not creating CSS file in destination

I am trying to set the Gulp tasks for styles with postcss, CSS modules etc., but for now only the watch task for the main HTML file is working, and it is not even creating the main CSS file nor the temp folder so I get the error in the console that it can not find the styles.css. It's driving me crazy for days but just cannot get to the bottom of it. Here is my file structure, pretty basic:
application -> views -> index.html
public -> gulp -> tasks -> styles.js, watch.js
-> styles (styles.css inside, base and modules for CSS subfolders)
And here are the styles and watch tasks:
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
notify: false,
server: {
baseDir: "../application/views"
}
});
watch('../application/views/index.html', function(){
browserSync.reload();
});
watch('../application/public/styles/**/*.css', function(){
gulp.start('cssInject');
});
});
gulp.task('cssInject', ['styles'], function(){
return gulp.src('../application/temp/styles')
.pipe(browserSync.stream());
});
Styles:
var gulp = require('gulp'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
mixins = require('postcss-mixins'),
hexrgba = require('postcss-hexrgba');
gulp.task('styles', function(){
return gulp.src('../application/public/styles/styles.css')
.pipe(postcss([cssImport, mixins, cssvars, nested, hexrgba, autoprefixer]))
.on('error', function(errorInfo){
console.log(errorInfo.toString());
this.emit('end');
})
.pipe(gulp.dest('../application/temp/styles'));
});
If someone can give a piece of advice I would be really grateful.

Concatenated files put into main.js just keeps stacking instead of clearing the file then adding the code

I'm trying to compile all my scripts into a single main.js file which I can then link to my index file. Problem is that all my script files are being concatenated and then just added to the main.js file, so if I save 3 times, I will basically have 3 copies of all my scripts concatenated and put in the main.js file.
I would like to either delete the main.js file each time I save and then run the concatenation, or just clean the file before adding the contents. Now if I try to delete the file using the del module, I receive an error stating that I can't delete files out of the working directory without forcing this action. I would like to avoid forcing this if possible.
I feel that there must be a more elegant way of doing this..
Here's my script task:
// Concat and compile our JS into a minified dist file
gulp.task('scripts', function() {
return gulp.src('../app/public/assets/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(concat('main.js'))
//.pipe(del(['../app/public/assets/scripts/main.js'])) <-- Doesn't work without forcing
.pipe(gulp.dest('../app/public/assets/scripts'))
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(notify({ message: 'Finished compiling scripts' }));
});
I usually do something like this (very simplified :) ):
var PARAMS = {
destPath: 'build',
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
],
// other
};
var TARGETS = {
dest: 'main.js', // dest file
extra: [
// This files are inclued only in .bundle.min.js version
// extra file here
],
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
]
};
gulp.task('connect', function() {
return connect.server({
livereload: true,
host: '0.0.0.0',
port: 8000
});
});
gulp.task('reload', ['build'], function () {
return gulp.src(['sandbox/**/*.html'])
.pipe(connect.reload());
});
gulp.task('watch', ['connect', 'build'], function () {
var src = [];
// other
src = src.concat(PARAMS.js);
return gulp.watch(src, ['reload']);
});
gulp.task('clean', function (done) {
return del(['build'], done);
});
gulp.task('build', ['clean'], function () {
return gulp.src(target.js);
.pipe(concat(target.dest))
.pipe(gulp.dest(PARAMS.destPath)) // Plain
.pipe(uglify())
.pipe(rename({ extname: '.min.js' })) // Minified
.pipe(gulp.dest(PARAMS.destPath))
.pipe(addsrc(target.extra))
.pipe(order(target.extra))
.pipe(concat(target.dest))
.pipe(rename({ extname: '.bundled.min.js' })) // Bundled
.pipe(gulp.dest(PARAMS.destPath));
});
gulp.task('default', ['build']);

Categories