Node.js - Stylus Middleware dest and src path in expressjs - css

i know there are some 'Stylus Middleware' question but still i haven't figure it out yet..
so I'd like to compile .styl file every i run node app.js
var express = require('express');
var stylus = require('stylus');
var nib = require('nib');
var app = express();
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.use(stylus.middleware({
src: __dirname + 'stylus',
dest: __dirname + 'stylesheets',
force: true,
compress: true
}));
i already create the static directory in public..
And this is my folder hirearchy (i deleted the node_modules for a while to get simple tree)
MyApp:
-public
- stylus
- stylesheets
- images
- javascript
-views
-routes
-app.js
-package.json
So with this code, everytime i ran node app.js stylus middleware wnt compile the style file in /public/stylus/style.styl and place the compiled file(css) in /public/stylesheets/style.css
Thankyou all :)

var express = require("express")
var stylus = require("stylus")
var path = require("path")
// var expressStylus = require("express-stylus")
var app = express();
app.use("/public", express.static(path.join(__dirname,"public")))
// If you are using stylus use this syntax
// stylus doesn't take on object as parameter
app.use(stylus.middleware(path.join(__dirname, 'public')));
/**
express-stylus module can take an object as a parameter
app.use(expressStylus.middleware({
src: path.join(__dirname, "public", "stylus"),
dest: path.join(__dirname, "public", "styleSheets"),
force: true,
compress: true
}))
*/
app.get("", function(request, response) {
response.render("index")
})
app.listen(app.get("port"), function() {
console.log("The server is running on http://localhost:%s", app.get("port"))
})
and I use this directory structure
- public
- style.styl
- views
- routes
- app.js
- package.json

Related

Gulp Browser Sync Issue: http://192.168.1.104:8080/ Not Working

I am a beginner in WordPress. I am learning to build a WordPress theme using underscores. After typing "gulp" in the command line, http://192.168.1.104:8080/ is being opened in the browser. It continues to load, but ended up with this error:
This page isn’t working
192.168.1.104 didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my gulp.js file:
var themename = 'kanonscores';
var gulp = require('gulp'),
// Prepare and optimize code etc
autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require('gulp-image'),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
// Only work with new or updated files
newer = require('gulp-newer'),
// Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages/';
// CSS via Sass and Autoprefixer
gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'expanded',
indentType: 'tab',
indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});
// Optimize images through gulp-image
gulp.task('images', function() {
return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
.pipe(newer(img))
.pipe(image())
.pipe(gulp.dest(img));
});
// JavaScript
gulp.task('javascript', function() {
return gulp.src([js + '*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest(js));
});
// Watch everything
gulp.task('watch', function() {
browserSync.init({
open: 'external',
proxy: 'kanonscores.com',
port: 8080
});
gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
gulp.watch(js + '**/*.js', ['javascript']);
gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
gulp.watch(root + '**/*').on('change', browserSync.reload);
});
// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
When I go inside "node_modules" of "gulp.dev" directory via NetBeans, I notice some errors in the folders of "browser-sync," "gulp" and "gulp-saas."
You can find the entire gulp.dev directory here:
https://drive.google.com/open?id=1HaFcW0dCMIH3t8Dyg8f8hcQwxfux0GnT
Should I attach the entire exercise files, including the WordPress files?
Try changing your gulp watch task proxy to 'localhost'
gulp.task('watch', function() {
browserSync.init({
proxy: 'localhost',
port: 8080
});
gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
gulp.watch(js + '**/*.js', ['javascript']);
gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
gulp.watch(root + '**/*').on('change', browserSync.reload);
});
My bad! I haven't launched WAMP. I am a poor beginner!

Webpack - Bundle only required CSS files for production

I have a Vue app that has 3 different css themes depending on what the 'brand' is set to. Right now it is working in development. I run an npm run dev command and pass in the brand, then set the brand variable to be globally accessible, and then in my main.js file I set the required css dynamically based on what the brand variable is.
var brand = window.__BRAND__;
require('../static/' + brand + '/css/typography.css')
require('../static/' + brand + '/css/header.css')
require('../static/' + brand + '/css/main.css')
require('../static/' + brand + '/css/footer.css')
file structure:
static
foo
css
bar
css
So if I run 'npm --brand=bar run dev' it will require '..static/bar/typography.css' etc.
This works great in my local environment; each has it's own distinct look. The issue I'm having now is with building the app for production. Webpack is somehow compiling ALL of the css files into one and I end up with a hybrid app that has some styling from each. Instead, I need it to compile the CSS with ONLY the files that are required. Here is my webpack.prod.conf file:
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
comparisons: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
]),
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
})
if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
and my config/index.js file:
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://localhost:3001',
changeOrigin: true
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

How to update css theme file in WordPress

I am confused on where to edit WordPress themes. I am new to WordPress and have a custom theme which main style.css file just imports the style for this theme like this:
#import url('assets/stylesheets/app.css');
I read that it is recommended to make a new child theme, but I don't see the need for that in my case, since I would like to almost completely change the css of the theme, so there is no need to keep the original theme files. Since, I tried to modify the file 'assets/stylesheets/app.css' I couldn't see any changes in the browser. Can I edit the styles there, or I need to do it in the WP admin dashboard somewhere?
I would like to build my scripts with gulp, which I set up like this:
var gulp = require('gulp');
var sass = require('gulp-sass');
var include = require('gulp-include');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var sourcemaps = require('gulp-sourcemaps');
var prefix = require('gulp-autoprefixer');
var connect = require('gulp-connect');
var browserify = require('gulp-browserify');
var livereload = require('gulp-livereload');
var browsersync = require('browser-sync');
var config = {
srcDir: './assets',
styles: {
src: '/scss/app.scss',
dest: '/stylesheets',
includePaths: [
'node_modules/foundation-sites/scss'
],
prefix: ["last 2 versions", "> 1%", "ie 9"]
},
scripts: {
src: '/js/app.js',
dest: '/js'
},
img: {
src: '/images/**/*',
dest: '/images'
}
};
var srcDir = './src',
destDir = './build';
gulp.task('styles', function() {
return gulp.src(config.srcDir + config.styles.src)
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: config.styles.includePaths,
sourceMap: true,
outFile: config.srcDir + config.styles.dest + '/app.css',
outputStyle: 'compressed'
}))
.pipe(prefix(config.styles.prefix))
.pipe(sourcemaps.write())
.on('error', sass.logError)
.pipe(gulp.dest(config.srcDir + config.styles.dest))
.pipe(browsersync.reload({ stream: true }));
});
gulp.task('scripts', function() {
gulp.src(config.srcDir + config.scripts.src)
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(gulp.dest(config.srcDir + config.scripts.dest))
});
gulp.task('include', function() {
return gulp.src(config.srcDir + config.img.src)
.pipe(gulp.dest(config.srcDir + config.img.dest));
});
gulp.task('watch', function () {
// Watch .scss files
gulp.watch(config.srcDir + config.styles.src, ['styles']);
// Watch .js files
gulp.watch(config.srcDir + config.scripts.src, ['scripts']);
});
gulp.task('default', ['styles', 'scripts', 'watch']);
So, not sure how can I do it utilizing gulp. Where can I change the theme without creating the child theme?
Where does the import of "app.css" happen - at the beginning or at the end of the "style.css" file? If it's at the beginning, the changed rules in "app.css" might be overwritten by the following "style.css" rules.

Using Sourcemaps with google chrome

i have tried to configure sourcemaps in less files. When I inspect an Element I see the correct less file with the file extension. So it seems to work
But when I do changes the file name for Example style.less:1120 change to style.css:129
What went wrong?
Another problem is, that chrome shows me only the style.less file. This file imports only my components. So instead of seeing component.less:10 i see style.less:221
My gulpfile:
var gulp = require('gulp');
var less = require('gulp-less');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var paths = {
scripts: ['client/js/**/*.coffee', '!client/external/**/*.coffee'],
images: 'client/img/**/*',
less: 'web/style/style.less'
};
gulp.task('less' , function() {
// Minify and copy all JavaScript (except vendor scripts)
// with sourcemaps all the way down
return gulp.src(paths.less)
.pipe(sourcemaps.init())
.pipe(less())
.pipe(rename(function(path) {
path.extname = ".css";
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('web/style/.'));
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(paths.less, ['less']);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch']);

gulp-sourcemap file extension issue

Trying to create a gulp file that picks up our LESS files and generates the appropriate .css, .min.css, and .css.map files. Close, but sourcemaps is writing the map to a file with the extension .css.min.css.
/// <vs BeforeBuild='less' SolutionOpened='less' />
/// <binding BeforeBuild='less' ProjectOpened='less' />
var gulp = require('gulp');
var less = require('gulp-less');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var minifycss = require('gulp-minify-css');
var pleeease = require('gulp-pleeease');
var rename = require('gulp-rename');
var mqpacker = require('css-mqpacker');
var csswring = require('csswring');
var postcss = require('gulp-postcss');
var processors = [
autoprefixer({ browsers: ["IE >= 9, firefox > 10, last 2 Chrome versions, last 2 safari versions, last 2 ios versions"] }),
mqpacker
];
gulp.task('less', function () {
gulp.src('./itims/Content/*.less', { base: './itims/content'})
.pipe(sourcemaps.init())
.pipe(less())
.pipe(postcss(processors))
.pipe(rename({
extname: '.css'
}))
.pipe(gulp.dest('./itims/content'))
.pipe(minifycss())
.pipe(sourcemaps.write('./'))
.pipe(rename({
suffix: '.min',
extname: '.css'
}))
.pipe(gulp.dest('./itims/content'));
});
As you might guess, your problem comes from the rename that is after the sourcemaps.write. You want to rename only *.css files, hence the following solution should do the trick :
Add gulp-if to your dependencies if not already present
var if = require('gulp-if');
Rewrite your task as follows :
gulp.src('./itims/content/*.less', {base: './itims/content'})
.pipe(sourcemaps.init())
.pipe(less())
.pipe(postcss(processors))
.pipe(gulp.dest('./itims/content'))
.pipe(minifycss())
.pipe(sourcemaps.write('./'))
.pipe(if('*.css', rename({extname: '.min.css'}))
.pipe(gulp.dest('./itims/content'));
Notes:
I removed your first rename as the less plugin already handles the renaming of *.less to *.css
Beware of the case in the path names. You mixed './itims/Content' and './itims/content'.

Resources