Command-line argument as var in Sass, for hardcoded CDN URL's on compile - css

For local HTML/Sass/Css developement we use libsass (via Grunt) to compile our Sass files to Css. The Css background-image URL's are root relative.
Sass
$dir-img: /img;
.header {
background-image: url(#{$dir-img}/header.jpg);
}
We'd like to change the URL to use a CDN when compiling for production server:
background-image: url(http://media.website.com/img/header.jpg);
Is there some solution to pass-in a command-line argument TO Sass so Sass can use a Sass #IF to switch the root-relative URL's to hard-coded CDN like URL's. Something like:
Command-line:
grunt sass:dist --cdnurl="http://media.website.com/img/"
Sass
Then Sass checks if the command-line argument was given:
#if using CDN {
$dir-img: cdnurl;
#else {
$dir-img: /img;
}
And then all IMG url's would use the CDN URL.

I couldn't find anything on libass command-line options to pass said vars. to Sass.
But eventually came up with a working version of my own! Have Grunt write a Sass config partial.
Pretty simple actually if your already using Grunt and Sass. We'd already had NodeJS and Grunt-cli installed on our staging (test) -server.
Sass setup
In Sass we already used a (larger) Sass config file which holds a few vars like:
_config.scss
$dir-font: '/assets/assets/fonts';
$dir-htc: '/assets/htc';
$dir-img: '/assets/images';
This config file holds much more config settings but I've updated these vars. in this config file to:
#import "_sourcepaths";
$dir-font: '/assets/fonts' !default;
$dir-htc: '/assets/htc' !default;
$dir-img: '/assets/images' !default;
Note the #import partial of _sourcepaths.scss. This smaller partial file is generated by Grunt. The Sass !default; is used as fallback vars. or you might not even need these anymore (are overwritten by Grunt).
Grunt setup
On the Grunt side I added a custom task that is only executed on our staging (or test) -server (for example during a build process). On our local machine we keep using root-relative paths for local development.
Grunt custom target configuration
module.exports = function(grunt) {
grunt.initConfig({
writeSassConfig: {
options: {
scss: './assets/scss/partials/_sourcepaths.scss',
dirFont: '/assets/fonts',
dirHtc: '/assets/htc',
dirImg: '/assets/images'
},
cdn: {
//pathprefix: 'http://cdn.website.com'
pathprefix: grunt.option('pathprefix') || ''
}
}
}
});
Example cdn Grunt target with hardcoded (http://cdn.website.com) or dynamic (via grunt.option command-line argument) pathprefix. See below at 'Running the Grunt task' how to run this. It also has a fallback || '' to empty, which actually resets the paths in the Sass config file to root-relative URL's.
Grunt custom task
Then the required Grunt task (for configuration above). This Grunt task writes the Sass partial to disk.
grunt.registerMultiTask('writeSassConfig', 'Write Sass config file to change source paths', function(){
grunt.config.requires(
this.name + '.options.scss',
this.name + '.options.dirFont',
this.name + '.options.dirHtc',
this.name + '.options.dirImg',
);
// Create Sass vars
var _thisOptions = this.options(),
pathprefix = this.data.pathprefix || '',
contents = "// Generated by Grunt for dynamic paths like a CDN server\n";
contents += "$dir-font: '" + pathprefix + _thisOptions.dirFont + "';\n";
contents += "$dir-htc: '" + pathprefix + _thisOptions.dirHtc + "';\n";
contents += "$dir-img: '" + pathprefix + _thisOptions.dirImg + "';\n";
grunt.file.write(_thisOptions.scss, contents);
});
Grunt aliased task
This creates a custom chained workflow of two tasks running after each other. The sass:dist is a regular Grunt task and target via grunt-sass (libsass) plugin. You are probably already using this.
grunt.registerTask('build-sasscdn', 'Generate Sass config for different Sass paths like a CDN server path', function(){
grunt.task.run(
'writeSassConfig',
'sass:dist'
);
});
Running the custom Grunt task
The pathprefix var., via grunt.option('pathprefix'), in above Grunt custom target is provided via grunt command-line argument:
grunt build-sasscdn --pathprefix="https://cdn.website.com"
This domainname can be changed by the staging (test) -server server-side-scripting language (like .NET/PHP/Ruby). The Sass config file _sourcepaths.scss is now changed by Grunt to:
_sourcepaths.scss
$dir-font: 'https://cdn.website.com/assets/fonts';
$dir-htc: 'https://cdn.website.com/assets/htc';
$dir-img: 'https://cdn.website.com/assets/images';
Remember that _sourcepaths.scss is imported by Sass. The Grunt alias task then runs the usual sass:dist target, which just re-compiles the Sass (on the staging / test server) WITH updated hard-coded CDN domain name paths in the Css.

Related

Is there any way to tell angular-cli (for angular 2) to generate minified version of css?

As the title says, when I run "ng serve" angular-cli generates normal css whereas I expect to get the minified version.
Is there any specific setting to use for angular-cli-build, or some additional plugin to install and use?
This is my angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(ts|js|js.map)',
'rxjs/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)',
'angular2-cookie/**/*.js'
]
});
};
ng build --prod --env=prod
or
ng serve --prod
Will minify and add a file hash for you.
the --prod tells it to minify hash, and gzip.
the --env=prod tells it to use your prod environment constants file.
which would look like this
You can use
# --env=<your_env>
# --no-sourcemap
# minify => ./minify.js
ng build --env=prod --no-sourcemap && node minify
minify.js
// npm i --save-dev minifier fs-jetpack
const jetpack = require('fs-jetpack');
const path = require('path');
const minifier = require('minifier');
const files = jetpack.list(path.join(__dirname, 'dist'));
console.log(files);
for (const file of files) {
if (/.*(\.js|\.css)$/g.test(file)) {
console.log(`Start ${file}`);
const filePath = path.join(__dirname, 'dist', file);
minifier.minify(filePath, {output: filePath});
}
}
console.log('End');
James' commands DO work and DO minify even when using ng serve --prod.
However you may see something like the following in Chrome and get confused:
That doesn't look minified does it!
Look more carefully and you'll see js:formatted indicating that the pretty print feature was enabled.
Opening the URL http://localhost:4200/main.5082a3da36a8d45dfa42.js directly in a new tab showed me that the CLI was indeed minifying it fully.
You can click the {} icon to turn this feature off, but it seems to like to disappear once the code has been pretty printed so you may need to reload the page and click it quickly.
In 2020 it is just enough to use --prod flag, when building project:
ng build --prod

Plug-in CSS files not removed from SystemJS built bundle

When I bundle the JavaScript files with the JSPM bundle command and I remove my own source files to obtain a third party library bundle, my CSS files are not removed from the bundle.
My grunt config looks like:
lib: { // third-party libraries bundle
files: {
"src/lib.bundle.js": tsAboutSrcFiles + " - [about/**/*] - [core/**/*]"
}
}
The CSS files that are part of the 'about' and 'core' directories are not removed and end up in the lib.bundle.js
config.js shows that the lib.bundle.js contains files such as:
"about/aboutbox.component.css!github:systemjs/plugin-css#0.1.22.js"
The question is: how do I remove these files from the 3rd party bundle?
Found a solution by trial and error, probably not the most elegant, but at least this works:
lib: { // third-party libraries bundle
files: {
"src/lib.bundle.js": tsAboutSrcFiles + " - [about/**/*] - [core/**/*] - [about/**/*!github:systemjs/plugin-css#0.1.22.js] - [core/**/*!github:systemjs/plugin-css#0.1.22.js]"
}
}

using execution directory as Gruntfile's file base

I'm trying to use Grunt to clean up a large project. For this specific example, I am trying to run unit tests and want to do so only for paths under the current grunt execution directory (i.e., the result of pwd).
I want one Gruntfile at the project root. I know grunt will find and execute this with no problem from any subdirectory. If I define my test runner options to look in "test/", it only runs tests under {project root/}test/. Is there a way to tell a project-level Gruntfile to make its paths (in all or in part) relative to the executing location?
Notes:
I don't need to be told "Why would you do this? Grunt should manage your whole project!" This is a retrofit, and until that halcyon day when it all works, I want/need it piecemeal.
To reiterate, "**/test/" isn't the answer, because I want only the tests under the current grunt execution directory.
--base also won't work, because Grunt will look for the Node packages at the base location.
I have, for similar situations, used a shared configuration JSON file that I've imported with grunt.config.merge(grunt.file.readJSON("../grunt-shared.json"));. However, that requires Gruntfiles in subfolders, as well as a hard-coded path to the shared file (e.g., ../), which seems tenuous.
I could write code to do some directory climbing and path building, but I'd like to make that a last resort.
Here's the solution I came up with (H/T to #firstdoit, https://stackoverflow.com/a/28763634/356016):
Create a single, shared JavaScript file at the root of the project to centralize Grunt behavior.
Each "sub-project" directory has a minimal, boilerplate Gruntfile.js.
Manually adjust Grunt's file base in the shared file to load from one node_modules source.
Gruntfile.js
/**
* This Gruntfile is largely just to establish a file path base for this
* directory. In all but the rarest cases, it can simply allow Grunt to
* "pass-through" to the project-level Gruntfile.
*/
module.exports = function (grunt)
{
var PATH_TO_ROOT = "../";
// If customization is needed...
// grunt.config.init({});
// grunt.config.merge(require(PATH_TO_ROOT + "grunt-shared.js")(grunt));
// Otherwise, just use the root...
grunt.config.init(require(PATH_TO_ROOT + "grunt-shared.js")(grunt));
};
Using a var for PATH_TO_ROOT is largely unnecessary, but it provides a single focus point for using this boilerplate file across sub-projects.
{ROOT}/grunt-shared.js
module.exports = function (grunt)
{
// load needed Node modules
var path = require("path");
var processBase = process.cwd();
var rootBase = path.dirname(module.filename);
/*
* Normally, load-grunt-config also provides the functionality
* of load-grunt-tasks. However, because of our "root modules"
* setup, we need the task configurations to happen at a different
* file base than task (module) loading. We could pass the base
* for tasks to each task, but it is better to centralize it here.
*
* Set the base to the project root, load the modules/tasks, then
* reset the base and process the configurations.
*
* WARNING: This is only compatible with the default base. An explicit base will be lost.
*/
grunt.file.setBase(rootBase);
require("load-grunt-tasks")(grunt);
// Restore file path base.
grunt.file.setBase(processBase);
// Read every config file in {rootBase}/grunt/ into Grunt's config.
var configObj = require("load-grunt-config")(grunt, {
configPath: path.join(rootBase, "grunt"),
loadGruntTasks: false
});
return configObj;
};

How to pass an option to a Grunt task using WebStorm?

I have a Gruntfile.js in my project, which is parsed by WebStorm (JetBrains IDE for Javascript). The parsed tasks appear in the Grunt view.
Considering the following task (see http://gruntjs.com/frequently-asked-questions#options) :
grunt.registerTask('upload', 'Upload code to specified target.', function(n) {
var target = grunt.option('target');
// do something useful with target here
});
How can I run grunt upload --target=staging using WebStorm ? I can't find a way to pass the option.
to specify custom CMD options (retrieved via grunt.option()) passed to Grunt task, use Tasks field of Grunt Run configuration, like: 'print -–echo=Hello' (or 'upload --target=staging' in your case)

Django Pipeline, Heroku, and SASS

I've been trying to get django-pipeline setup so that I can compile and concat my assets. I would also like to remove the compiled css files from my repository to avoid merge conflicts in pull requests.
I've been trying to get django-pipeline to compile the files as part of the deploy process but can't figure this out. I use SASS to write my CSS. My pipeline settings look like this:
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_CSS = {
'main': {
'source_filenames': (
'sass/blah.scss',
'sass/main.scss',
),
'output_filename': 'css/main.css',
'extra_context': {
'media': 'screen',
},
},
}
PIPELINE_COMPILERS = (
'pipeline.compilers.sass.SASSCompiler',
)
This works great locally, and generates .css files in my /sass folder, which are then combined to make the main.css file. If I check those CSS files into my git repository and push to Heroku, it also works fine. However, if I ignore them, which I would like to do so that I'm not committing compiled files, then django-pipeline can't find the files to combine. I'm not sure how I can get the sass compilation working on Heroku and I can't find anything about it.
I can provide more information about my setup if needed, hopefully somebody knows something about this!
OK, here's how I got this working using Compass to compile my SASS files.
Use multiple Heroku buildpacks - Heroku Buildpack Multi
Put the following in your .buildpacks file
https://github.com/heroku/heroku-buildpack-ruby.git
https://github.com/heroku/heroku-buildpack-nodejs
https://github.com/heroku/heroku-buildpack-python.git
Create a Gemfile with compass and any other requirements you have. Here's mine:
source 'https://rubygems.org'
ruby '1.9.3'
gem 'bootstrap-sass'
gem 'compass'
Create a config.rb file. Here's mine. As you can see it, requires the bootstrap-sass that I included in my Gemfile:
# Require any additional compass plugins here.
require 'bootstrap-sass'
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "app_folder/static/css"
sass_dir = "app_folder/static/sass"
images_dir = "app_folder/static/images"
output_style = :compact
more details on config.rb can be found here
Install node packages (django-pipeline wants yuglify). You'll need a package.json file:
{
"dependencies": {
"yuglify": "0.1.4"
},
"engines": {
"node": "0.10.x",
"npm": "1.3.x"
},
"repository": {
"type": "git",
"url": "your repo url"
}
}
almost ready...
when Heroku runs the ruby buildpack, it will look for a rake task called assets:precompile. So now you'll need to add a Rakefile with the following:
namespace 'assets' do
desc 'Updates the stylesheets generated by Sass/Compass'
task :precompile do
print %x(compass compile --time)
end
end
this will put compile your stylesheets. You need to make sure you set the output (back in config.rb) to the place that django-pipeline is looking for CSS files (shown in the original question).
You should get rid of this part in the original question as django-pipeline isn't compiling your SASS for you:
PIPELINE_COMPILERS = (
'pipeline.compilers.sass.SASSCompiler',
)
That should be it! Deploys should just work now, and it didn't really add a significant amount of time to my deploy process.
All in all, it amounts to a lot of setup, but for me it was well worth it as I no longer have to commit compiled files into the repository, which was causing a lot of merge conflicts when working with branches and pull requests.
I would like to figure out how to do this using only two buildpacks (obviously only one would be ideal but I don't know if it's possible). The problem is trying to find binary paths so that pipeline can do it's thing when it doesn't find the defaults. I'm not sure if the reason I can't do this is because of how Heroku is installing things, or because there is a bug in django-pipeline, but right now this is good enough for me.
If you try this and it doesn't work for you, let me know, if I missed something I'm happy to make updates.
I don't want to take away from your excellent solution, but I tried this today and found a few differences that made things simpler for me - likely due to updates in django-pipeline and/or Heroku. My full solution is below, in case anyone else comes looking.
Add the 3 buildpacks to Heroku:
heroku buildpacks:set https://github.com/heroku/heroku-buildpack-ruby.git
heroku buildpacks:add https://github.com/heroku/heroku-buildpack-nodejs
heroku buildpacks:add https://github.com/heroku/heroku-buildpack-python.git
Add django-pipeline and django-pipeline-compass to requirements.txt:
django-pipeline==1.5.2
django-pipeline-compass==0.1.5
Create a Gemfile to install Sass:
source 'https://rubygems.org'
ruby '2.1.5'
gem 'bootstrap-sass'
Create a package.json file to install Yuglify:
{
"dependencies": {
"yuglify": "0.1.4"
},
"engines": {
"node": "0.10.x",
"npm": "1.4.x"
}
}
I did not need a Rakefile or config.rb.
For reference, here are relevant settings from my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '_generated_media')
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
'pipeline_compass.compiler.CompassCompiler',
)
PIPELINE_YUGLIFY_BINARY = os.path.join(BASE_DIR, 'node_modules', '.bin', 'yuglify')
And I also had to add this entry to urls.py:
url(r'^static/(?P<path>.*)$', serve, kwargs={'document_root': settings.STATIC_ROOT})
Hope it helps someone!
You may need to set PIPELINE_SASS_BINARY so that django-pipeline can find your SASS compiler.
You can use the libsass compiler for django-pipeline that uses Sass packaged as a Python package:
pip install libsasscompiler
Update your config:
PIPELINE['COMPILERS'] = (
'libsasscompiler.LibSassCompiler',
)
The default Yuglify compressor is also a problem on Heroku, which you can temporarily overcome by disabling it. This is my config for enabling Sass on Django for example:
PIPELINE = {
'COMPILERS': (
'libsasscompiler.LibSassCompiler',
),
'STYLESHEETS': {
'main': {
'source_filenames': (
'styles/main.scss',
),
'output_filename': 'css/main.css'
},
},
# disable the default Yuglify compressor not available on Heroku
'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor',
'JS_COMPRESSOR': 'pipeline.compressors.NoopCompressor'
}
The longer-term solution would be to move towards a JS-only build toolchain (as most projects are doing). Rails integrates pretty nicely with Webpack for example and is maintained by the same team. Until that happens in Django (if ever) and trickles into the Heroku Python builpack, you can use Heroku's multiple buildpacks and add an official Node buildpack step that runs npm install; npm run build for you.

Resources