styles dont connect when loading local server - css

my dir looks like that :
|-project
-gulpfile.js
|-build
-index.html
|-js
-app.min.js
-vendors.min.js
|-styles
-all.css
-vendors.min.css
i inject the css and js files with this gulp task:
gulp.task('index',function () {
return gulp.src('src/index.html')
.pipe(inject(gulp.src(['**/vendors.min.css','**/vendors.min.js','**/app.min.js','**/all.css'], {read: false})))
.pipe(gulp.dest('build'))
.pipe(livereload());
})
i set up a local server with node.js,when i do the request , the html file loads up,but the .js and .css files dont connect for some reason.Although when i check page's source code at output their paths are written in.
<!-- inject:css -->
<link rel="stylesheet" href="/build/styles/vendors.min.css">
<link rel="stylesheet" href="/build/styles/all.css">
<!-- endinject -->
when i hover on one of them it shows :
http://localhost:5000/build/styles/all.css
i use this task for setting the server :
gulp.task('connect', function() {
connect.server({
root: 'build',
livereload: true,
port: 5000
});
});
EDIT
any recommendation about how to make it on hovering look like
localhost:5000/styles/all.css

If the build folder is the root of the server, you shouldn't be including it in the path of the js and css files. This is failing because you are trying to reference a build folder inside the build folder.
Change your injection of css to the following:
<link rel="stylesheet" href="styles/vendors.min.css">
<link rel="stylesheet" href="styles/all.css">

Related

Generating pdf file from express-handlebars render with html-pdf library, css files not working

I'm trying to generating a pdf file which is generated from express-handlebars rendering. However, some css files don't seem to be working.
Bootstrap are still working okays, but the custom css (i'm using a theme) is not working. I have tried phantomjs config (--web-security=false,...), switching css folder directory from local to the server. But none of them seems to be working. Images are working fine.
generating html and creating pdf files
var config = {
format: "A4",
orientation: "landscape",
base: "http://127.0.0.1:3002/uploads/theme/",
timeout: 100000,
phantomArgs: ["--web-security=false","--local-to-remote-url-access=true"]
}
var html = await hbs.render('./views/pdf.handlebars', data)
await fs.writeFile("pdf.html", html, function(err) {
if(err) {
return console.log(err);
}
})
var fileName = uuid.v4()
await pdf.create(html, config).toFile(`./downloads/${fileName}.pdf`, function (err, res) {
if (err) return console.log(err);
response.send({ success: true, data: { downloadURL: fileName } })
including css files:
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/animate.min.css">
server receiving calls from css files:
Imgur
Expecting results:
Imgur
Actual result:
Imgur
As you can see, bootstrap and font-awesome are working fine, but the "style.css" is not working. Anyone have any idea about this problems? Many thanks in advance!
Your server code is reading only HTML files and not css files , so css is actually being not used, use inline css.
I am also looking for methods to write separate HTML and CSS and merge to form pdf.

Webpack-React with server-side-rendering: linking to css file in server template with hash name

I'm preparing a starter for react from scratch, here is the code: https://github.com/antondc/react-starter
I managed to set up bundling for client and server, with css modules and less, and now I'm with server side rendering. I'm doing that with a js template:
// src/server/views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INDEX.EJS</title>
<link rel="stylesheet" type="text/css" href="assets/index.css">
</head>
<body>
<div id="app"></div>
<script src="/assets/bundle.js"></script>
</body>
</html>
As you see, the link to the css file is harcoded there. But in my Webpack configuration I have this file name hashed, because I want to prevent caching from browsers when I update the code on development.
I am wondering how can I link the css file there. Now in the template I have href="assets/index.css, but the css file is in /dist/assets/d47e.css.
It would be great if would be possible to do something like href="assets/*.css, but is not possible, so what is the common approach for a problem like this one?
Thanks!
It depends.
Step 1: Get the current asset name
To get the current name of the generated webpack css/js files, you can use the assets-webpack-plugin. This will (with default config) generate an assets.json file in your output folder with essentially this structure:
{
"bundle_name": {
"asset_kind": "/public/path/to/asset"
}
}
Step 2a: Your html is rendered from a template (pug/jade/what ever)
// in your render code
const assets = require('<webpack-output-folder>/assets.json');
// ...
res.render('template', {
scripts: [{src: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.js}` }],
links: [{href: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.css}` rel: 'stylesheet' }],
});
// in your template (example for pug)
// ...
each link in links
link(rel=link.rel href=link.href)
// ...
each script in scripts
script(src=script.src)
// ...
Step 2b: Your html is static
You need to update the html (using a script) with the information from the asset.json file. This script needs to be run after webpack. Something like
const assets = require('<webpack-output-folder>/assets.json');
const fs = require('fs');
const css = /assets\/[a-z0-9]*\.css/i;
const js = /assets\/[a-z0-9]*\.js/i;
fs.readFile('<yourhtml>.html', (err, data) => {
// ... (error handling)
const updatedCss = data.replace(css, assets.myEntryPointName.css);
const updatedJs = updatedCss.replace(js, assets.myEntryPointName.js);
fs.writeFile('<yourhtml>.html', updated, (err) => {
// ... (error handling)
});
});
You can use HTMLWebpackPlugin to generate an HTML file that will have your JS and CSS output inserted.

Can't get GulpFile to act the way I want, missing something?

Trying to set up gulp and one of the steps is frustrating. I am following a tutorial and can't get it to work right.
https://css-tricks.com/gulp-for-beginners/
Basically, I want to create a build task that compiles sass, concats the css files, minimizes it, and output it to the public folder. Here is my code for my index.html. (Simplified).
<!DOCTYPE html>
<html lang="en">
<head>
<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">
<!--build:css css/styles.min.css -->
<link rel="stylesheet" href="scss/styles.scss">
<!-- endbuild -->
</head>
<body>
</body>
</html>
Now here is my Gulpfile.js
var gulp = require('gulp'),
sass = require('gulp-sass'),
useref = require('gulp-useref'), // Use to concatenate files
gulpIf = require('gulp-if'),
cssnano = require('gulp-cssnano'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
imagecache = require('gulp-cache'),
del = require('del'),
runsequence = require('run-sequence');
/* ********************************* */
// PRODUCTION TASKS ONLY \\
/*Used to start with a clean slate on the public folder */
gulp.task('clean:public', function () {
return del.sync('public');
})
gulp.task('watch:prod', function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
});
gulp.task('sass:prod', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('public/css'))
});
gulp.task('useref:prod', function () {
return gulp.src('src/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('public'));
});
gulp.task('images:prod', function () {
return gulp.src('src/images/**/*.+(png|jpg|gif|svg)')
.pipe(imagecache(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({plugins: [{removeViewBox: true}]})
])))
.pipe(gulp.dest('public/images'));
});
gulp.task('cssimages:prod', function () {
return gulp.src('src/css/cssimages/**/*.+(png|jpg|gif|svg)')
.pipe(imagecache(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({plugins: [{removeViewBox: true}]})
])))
.pipe(gulp.dest('public/css/cssimages'));
});
/* BRING EVERYTHING TOGETHER */
gulp.task('build:prod', function (callback){
runsequence
(
'clean:public',
['sass:prod','useref:prod','images:prod', 'cssimages:prod'],
callback
)
})
As per the tutorial, this should create a file in the public folder under css names styles.min.css
This file should also already be compiled down from sass. I did an example styles.scss and inside it I have.
$bgcolor : yellow;
body {
background: $bgcolor;
}
div {
width: 100px;
height: 20px;
}
When I run gulp build:prod , this is what it outputs in styles.min.css
$bgcolor:#ff0;body{background:$bgcolor}div{width:100px;height:20px}
The files minimizing fine but i can't get the sass part run right and compile when use the build task.
^^^ As you see, instead of sassing the file and then concatenating the file, it create 2 files. I'm trying to have gulp sass the file first, and then have useref move the file to the public folder and rename it to styles.min.css
It seems I'm missing something somewhere or not sourcing/destinating to the right folders?
If I run gulp sass:prod, it works fine. But can't seem to get my build task to run right I'm stumped.
From the article that you have mentioned,
Gulp-useref concatenates any number of CSS and JavaScript files into a
single file by looking for a comment that starts with "". Its syntax is:
<!-- build:<type> <path> --> ... HTML Markup, list of script / link tags. <!-- endbuild -->
path here refers to the target path of the generated file.
According to the document you have specified the following.
<!--build:css css/styles.min.css -->
<link rel="stylesheet" href="scss/styles.scss">
<!-- endbuild -->
So the useref will copy the styles from styles.scss and creates styles.min.css and pastes the scss styles. That is the reason you are getting scss styles in the minified styles.min.css
To achieve what you wanted you have to modify your sass:prod dest path like below.
gulp.task('sass:prod', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('src/css'))
});
and in the html, you have to reference the css file.
<!--build:css css/styles.min.css -->
<link rel="stylesheet" href="css/styles.css">
<!-- endbuild -->
And also as specified by #Mark, it is better to modify the run-sequence to make sure that the sass:prod task completes before the useref:prod task.
gulp.task('build:prod', function (callback){
runsequence
(
'clean:public','sass:prod',
['useref:prod','images:prod', 'cssimages:prod'],
callback
)
})
From the run-sequence documentatin :
You can still run some of the tasks in parallel, by providing an array of task names for one or more of the arguments.
So, in your tasks array :
['sass:prod','useref:prod','images:prod', 'cssimages:prod'],
these tasks run in parallel. There is no guarantee that the 'sass:prod' task will complete before the 'useref:prod' task. If you want that to happen change to:
gulp.task('build:prod', function (callback){
runsequence
(
'clean:public',
'sass:prod',
['useref:prod','images:prod', 'cssimages:prod'],
callback
)
})

Enyo error: "Uncaught referenceError: App is not defined"

I am getting the error: "Uncaught referenceError: App is not defined" in my JS console when loading this Enyo app on my localhost. I am brand new to Enyo so I am still trying to learn the concepts of kinds and components.
app.js (in source folder):
enyo.kind({
name: "App",
kind: "FittableRows",
classes: "enyo-fit enyo-unselectable",
components: [
{
kind: "onyx.Toolbar",
layoutKind:"FittableColumnsLayout",
components: [
{
kind:onyx.Button,
style:"width:80px;background:green;",
ontap:"handleBtnBack",
content:"Back"
},
{
content:"Header",
style:"text-align:center;",
fit:true
},
{
kind:onyx.Button,
style:"width:80px;background:red;",
ontap:"handleBtnNext",
content:"Next"
}
]
},
{
kind: "Scroller",
horizontal:"hidden",
touch:true,
fit:true,
thumb:true,
components:[
{
tag:"h1",
//This is how we insert css class.
classes:"padding15px",
content:"This is content area...Hello World!!!"
}
]
},
{
kind: "onyx.Toolbar",
// The footer
layoutKind:"FittableColumnsLayout",
components:[
{
kind:"onyx.Button",
content:"Go Next Page",
ontap:"handleBtnNextPage",
fit:true
}
]
}
],
create: function(){
this.inherited(arguments);
console.log("App is created in memory");
},
rendered : function(){
this.inherited(arguments);
console.log("App is created in rendered into DOM");
},
handleBtnNextPage : function(inSender,inEvent){
new Page2().renderInto(document.body);
},
handleBtnNext: function(inSender,inEvent){
new Page2().renderInto(document.body);
},
handleBtnBack: function(inSender,inEvent){
//For each enyo event handler comes with inSender, the control that sends the event and the inEvent the actual event itself.
alert("Back Button");
}
});
package.js (in source folder):
enyo.depends(
// Layout library
"$lib/layout",
// Onyx UI library
"$lib/onyx", // To theme Onyx using Theme.less, change this line to $lib/onyx/source,
//"Theme.less", // uncomment this line, and follow the steps described in Theme.less
// CSS/LESS style files
"../assets/css/app.css",
// Include our default entry point
"App.js",
"Page2.js"
);
index.html (in root folder):
<!--My Copy-->
<!DOCTYPE html>
<html>
<head>
<title>IsGoodStuff.com Tutorial #2</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="shortcut icon" href="assets/favicon.ico"/>
<script src="enyo/enyo.js" type="text/javascript"></script>
<!-- -->
<script src="package.js" type="text/javascript"> </script>
</head>
<body>
<script type="text/javascript">
new App().renderInto(document.body);
</script>
</body>
</html>
If your index.html is in your root folder, but the main package.js is in the source folder, it's probably your script tag that loads package.js. Try:
<script src="source/package.js" type="text/javascript"> </script>
You haven't supplied Page2 but it appears the code would work as-is.
Here's a fiddle showing the working page: http://jsfiddle.net/kgxvg7Lw/1/
Some thoughts:
1) Are you using a case-sensitive file system? You show app.js but your package.js has App.js (capitalized).
2) Are you certain there are no parse errors in the console?
Now, that said... You probably don't want to reload a new app for every 'page' switch. Usually, you would use something like Panels to allow the app to control the content that appears on the screen and just navigate among the panels as needed.

cssmin not correctly handling #import

I am using cssmin on files containing #imports. cssmin is recursively importing local files correctly, but for imports that point to a URL the imports are left inline. This makes the resulting minified CSS invalid because # rules must be at the beginning of the file. Does anyone know a good solution or workaround to this problem?
I have exactly the same problem with cssmin and #import, and i found a solution with grunt concat:
Create a concat grunt task that:
Put #import url in the begining of mified css file and replaces references of #imports url for "".
Execute task concat:cssImport after cssmin task.
Grunt task Code: to execute (concat:cssImport)
grunt.initConfig({
concat: {
cssImport: {
options: {
process: function(src, filepath) {
return "#import url(http://fonts.googleapis.com/css?family=Roboto:400,300,900);"+src.replace('#import url(http://fonts.googleapis.com/css?family=Roboto:400,300,900);', '');
}
}
},
files: {
'your_location_file_origin/file.full.min.css': ['your_location_file_destination/file.full.min.css']
}
} )}
My inspiration comes from https://github.com/gruntjs/grunt-contrib-concat#custom-process-function.
I added the processImport: false option to grunt.
'cssmin': {
'options': {
'processImport': false
}
}
Use the following process:
Install node-less
import the files by compiling with less first
minify with cssmin
References
node-less
LESS compile error
I had something like this in the styles.scss:
#import url(custom-fonts.css);
My problem was the #import wasn't able to find the files because the root path was missing. Here's what I did with yeoman angular generator Gruntfile.js config:
cssmin: {
options: {
root: '<%= yeoman.dist %>/styles/'
}
},
Useful link grunt-contrib-cssmin issue #75
I know this question for a very long time but i post this for anybody that looking for this issue on stack overflow ... just put your code in /!..../ like this:
/*! * #import url('//fonts.googleapis.com/cssfamily=Roboto:300,400,400i,500,700,700i'); */
it will be include in your destination min css but don't forget to use remote import in top of your page.
Putting the imports at the top of my scss didn't work for me,I ended up importing the external stylesheets directly from the html:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Roboto:400,300"
rel="stylesheet">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
......
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/app.css -->
<link el="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="styles/app.css">

Resources