I'm new with Grunt - csslint plugin, after I run and cssLint task complete, there are many and many errors and warnings that I can't follow. So how to config task just print out the errors, not warning??
If you use grunt-contrib-csslint you can specify the options in a .csslintrc file.
From the grunt-contrib-csslint Readme:
Options
Any specified option will be passed through directly to csslint, thus
you can specify any option that csslint supports. The csslint API is a
bit awkward: For each rule, a value of false ignores the rule, a value
of 2 will set it to become an error. Otherwise all rules are
considered warnings.
Assuming you have a structure like this:
├── .csslintrc
├── Gruntfile.js
├── css
│ └── foo.css
├── node_modules
└── package.json
.csslintrc
{
"ignore": [
"adjoining-classes",
"box-model",
"box-sizing",
"bulletproof-font-face",
"compatible-vendor-prefixes",
"display-property-grouping",
"duplicate-background-images",
"duplicate-properties",
"empty-rules",
"fallback-colors",
"floats",
"font-faces",
"font-sizes",
"gradients",
"ids",
"import",
"import-ie-limit",
"important",
"known-properties",
"non-link-hover",
"order-alphabetical",
"outline-none",
"overqualified-elements",
"qualified-headings",
"regex-selectors",
"rules-count",
"selector-max",
"selector-max-approaching",
"selector-newline",
"shorthand",
"star-property-hack",
"text-indent",
"underscore-property-hack",
"unique-headings",
"universal-selector",
"unqualified-attributes",
"vendor-prefix",
"zero-units"
]
}
reference: https://github.com/CSSLint/csslint/wiki/Command-line-interface
Gruntfile
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
csslint: {
strict: {
src: ['css/*.css']
},
lax: {
options: {
csslintrc: '.csslintrc'
},
src: ['css/*.css']
}
}
});
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.registerTask('default', ['csslint:lax']);
};
Then grunt will report only errors and grunt csslint:strict will report warnings and errors.
Related
I am working on a project consisting of three parts: a Client, a Server and a Common directory which contains things I want to import from both the Client and the Server. Everything can use both JS and TS. (Thanks to the babel-typescript preset)
Directory structure
Here is how it looks like:
root/
├── babel.config.js
├── Common/
│ ├── helper1.ts
│ ├── helper2.ts
│ ├── helper3.js
├── Client/
│ ├── src/
│ │ └── file1.js
│ └── .babelrc.js
└── Server/
├── src/
│ └── file1.js
└── .babelrc.js
Babel config files
Here is what my root/babel.config.js looks like:
module.exports = {
presets: ["#babel/preset-typescript"],
plugins: [
["#babel/plugin-transform-for-of", { assumeArray: true }],
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-json-strings",
["#babel/plugin-proposal-decorators", { legacy: true }],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-logical-assignment-operators",
"#babel/plugin-proposal-optional-chaining",
["#babel/plugin-proposal-pipeline-operator", { proposal: "minimal" }],
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-do-expressions",
"#babel/plugin-proposal-function-bind",
],
};
And here is what my Server/.babelrc.js looks like:
const moduleAlias = require("./tools/module-alias");
const rootConfig = require("../babel.config");
module.exports = {
presets: [
...rootConfig.presets,
[
"#babel/preset-env",
{
targets: {
node: "current",
},
exclude: ["transform-for-of"],
},
],
],
plugins: [
...rootConfig.plugins,
[
"babel-plugin-module-resolver",
{
root: ["."],
alias: moduleAlias.relativeAliases,
extensions: [".js", ".ts"],
},
],
],
};
I will omit the Client/.babelrc.js since it's very similar to the Server one.
Basic test files
Here is an example Common/helper3.js file:
function doubleSay(str) {
return `${str}, ${str}`;
}
function capitalize(str) {
return str[0].toUpperCase() + str.substring(1);
}
function exclaim(str) {
return `${str}!`;
}
const result = "hello" |> doubleSay |> capitalize |> exclaim;
console.log(result);
And inside Server/src/index.js I just import the file Common/helper3.js.
The error
Then, inside the Server directory, I do this:
npx babel-node src/index.js -x .ts,.js
Which prints the following error:
const result = "hello" |> doubleSay |> capitalize |> exclaim;
^
SyntaxError: Unexpected token >
I am definitely sure this error is related to my "strange" directory structure since it's fine when I put this exact file under Server/src.
The question
How can I keep this directory structure and tell Babel to use a config when it processes files within the Common directory?
I don't use Lerna or anything. I have setup special aliases that resolve $common to ../Common where needed. I know there is no issue with this since the file is properly found by Babel (otherwise I would get a "File not found" error)
Note
This babel structure is one of my attempt to fix the issue above. Originally I only had one babel.config.js inside Server and another inside Client. I thought having one at the root would solve this problem but it didn't change anything.
Edit after searching a lot more:
After taking a look at the babel code to find the config parsing, I noticed that this line : https://github.com/babel/babel/blob/8ca99b9f0938daa6a7d91df81e612a1a24b09d98/packages/babel-core/src/config/config-chain.js#L456 is called (null is returned).
I printed everything in this scope and noticed that babel automatically generates an only parameter containing the cwd. (Effectively saying that my babel.config.js doesn't affect my common directory despite being "above" is in the directory hierarchy).
I decided to try overloading it in the command line and arrived at this command:
npx babel-node src/index.js --root-mode upward -x .ts,.js --only .,../Common/ --ignore node_modules
(Added --only and --ignore)
This made me progress a bit: instead of failing to parse advanced syntax (pipeline operator) in js files, it failed on a ts failing, saying
export const accountStatus = Object.freeze({
^^^^^^
SyntaxError: Unexpected token export
What I don't understand is how it can parse the pipeline operator but not the typescript file even though both the pipeline plugin and the typescript are inside the same babel.config.js
Edit after solving this last issue:
Adding --only and --ignore made it work. The other issue was because I forgot to add the #babel/plugin-transform-modules-commonjs plugin and it was not able to resolve the import.
The slight change I did was adding ignore: ["**/node_modules"], to my root babel.config.js file and change my command to use those arguments: --root-mode upward -x .ts,.js --ignore __fake__.
Adding a random --ignore is enough to prevent babel from guessing by itself.
This is the solution I use and it works fine even though it's not very elegant.
I'm trying to compile my templates via grunt nunjucks-2-html:
this is my simplified grunt file:
module.exports = function(grunt) {
grunt.initConfig({
nunjucks: {
options: {
data: {},
paths: '/templates/'
},
render: {
files: [
{
expand: true,
src: '*.html',
cwd: '/templates',
dest: 'build',
ext: '.html'
}
]
}
}
});
grunt.loadNpmTasks('grunt-nunjucks-2-html');
};
my folder structure looks like this:
```
project
│ Gruntfile.js
│
└───templates
│ index.html
│ foo.html
│
└───build
```
When i run grunt nunjucks i got the following error:
"Running "nunjucks:render" (nunjucks) task No files specified."
So obviously nunjucks can't find my templates.
I have no idea where to config the template path, to me my gruntfile seems valid. If you have any idea, I would be glad.
Thank you!
The __dirname variable references the directory the Gruntfile lives in.
You could try using paths: __dirname + '/templates/' or just simply paths: 'templates' as described in the nunjucks-2-html npm documentation.
This seems like a basic question but I can't figure out how to do it. This is how to do it in gulp.
I want when I save a file with a jshint error to fail the Grunt build. The output states that jshint failed but Grunt still completes successfully.
grunt.initConfig({
watch: {
js: {
files: ['/scripts/{,**}/*.js'],
tasks: ['newer:jshint:all']
}
}
})
I know there is grunt.fail but how would I use it here?
The following gist will report a jshint error via the CLI and fail to execute any subsequent build steps when saving the .js file.
You will need to adapt according to your requirements :
Directory structure:
project
│
├──package.json
│
├───scripts
│ │
│ └───test.js
│
├─── Gruntfile.js
│
└───node_modules
│
└─── ...
package.json
{
"name": "stack40031078",
"version": "0.0.1",
"description": "Answer to stack question 40031078",
"author": "RobC",
"license": "Apache-2.0",
"devDependencies": {
"grunt": "^1.0.1",
"grunt-contrib-jshint": "^1.0.0",
"grunt-contrib-watch": "^1.0.0",
"grunt-newer": "^1.2.0"
}
}
Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// VALIDATE JS
jshint: {
// Note we're using 'src:' instead of 'all:' below.
files: {
src: './scripts/{,**}/*.js'
},
options: {
// Use your jshint config here or define them in
// a separate .jshintrc file and set the flag to:
//
// jshintrc: true
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
smarttabs: true,
globals: {}
}
},
// WATCH THE JS FILES
watch: {
js: {
files: ['./scripts/{,**}/*.js'],
// NOTE: we're not using 'newer:jshint:all' below, just 'newer:jshint'
tasks: ['newer:jshint' /* <-- Add subsequent build tasks here. E.g. ,'concat' - A registered task can also be added. E.g. 'default' */]
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.registerTask('default', [
]);
};
test.js
console.log('Hello World');
var test = function() {
return 'test';
};
Testing the demo gist
cd to the project directory
run $ npm install
run $ grunt watch
Open and make a simple edit to test.js, (e.g. add a new line to the end of the file), and save the change.
The CLI reports the error as follows:
Running "jshint:files" (jshint) task
./scripts/test.js
1 |console.log('Hello Universe');
^ 'console' is not defined.
>> 1 error in 1 file
Warning: Task "jshint:files" failed. Use --force to continue.
Aborted due to warnings.
Completed in 0.965s at Fri Oct 14 2016 10:22:59 GMT+0100 (BST) - Waiting...
NOTE:
Any subsequent build tasks specified in the tasks array of the watch.js object, (e.g. concat as per commented in the Gruntfile.js), will not be invoked using this gist as the jshint task fails (... and the concat task has not been defined of course!).
However, when the JavaScript file/s successfully pass the jshint task, any subsequent build tasks that are defined in the tasks array of the watch.js object will be invoked.
I hope this helps!
I'm struggling to make gulp-watch behave as I desire. This small project is tooling to build HTML5 emails templates from Jade+SASS, in a repeatable way. The directory structure is as such:
.
├── Gulpfile.coffee
├── Gulpfile.js
├── build
│ ├── hello-world.html
│ └── styles
│ └── ink.css
├── node_modules
│ ├── ...snip...
├── package.json
└── source
├── hello-world.jade
├── layouts
│ └── default.jade
└── styles
└── ink.scss
My wish list is thus:
Build all templates when styles or templates change. This is what I can't do
Don't have a seaerate "cold" start, always use the gulp incremental build. (This seems to work)
Live reload would reload the browser, that'd be cool. (This too)
The Gulpfile, in CoffeeScript notation for brevity is included below, it's predominantly based on the documentation Incremental rebuilding, including operating on full file sets.
gulp = require 'gulp'
inlineCss = require 'gulp-inline-css'
jade = require 'gulp-jade'
marked = require 'gulp-marked'
plumber = require 'gulp-plumber'
rename = require 'gulp-rename'
sass = require 'gulp-sass'
cached = require 'gulp-cached'
util = require 'gulp-util'
watch = require 'gulp-watch'
webserver = require 'gulp-webserver'
styleGlob = "source/styles/*.scss"
templateAndLayouysGlob = "source/**/*.jade"
templateGlob = "source/*.jade"
styleChangeHandler = (event) ->
if event.type is "deleted"
delete cached.caches.scripts[event.path]
templateChangeHandler = (event) ->
if event.type is "deleted"
delete cached.caches.templates[event.path]
gulp.task "styleWatcher", ->
gulp.src(styleGlob)
.pipe(cached('styles'))
.pipe(watch(styleGlob))
.pipe(sass())
.pipe(gulp.dest("build/styles"))
.on('error', util.log)
gulp.task "templateWatcher", ->
gulp.src(templateGlob)
.pipe(cached('templates'))
.pipe(watch(templateGlob))
.pipe(jade(pretty: true))
.pipe(inlineCss())
.pipe(gulp.dest("build/"))
.on('error', util.log)
gulp.task 'webserver', ->
buildPath = 'build/'
gulp.src(buildPath)
.pipe(webserver({
livereload: true,
directoryListing: {
enable: true,
path: buildPath
},
open: true
}))
gulp.task "watch", ->
styleWatcher = gulp.watch(styleGlob, ["styleWatcher"])
styleWatcher.on 'change', styleChangeHandler
templateWatcher = gulp.watch(templateGlob, ["templateWatcher"])
templateWatcher.on 'change', templateChangeHandler
# I would expect this to fire when something in build/styles/*.css
# is updated by the style watcher?
templateStyleWatcher = gulp.watch('build/styles/*.css', ["templateWatcher"])
templateStyleWatcher.on 'change', templateChangeHandler
gulp.task "default", ["styleWatcher", "templateWatcher", "watch", "webserver"]
If it were possible, and I'd written this watcher in GNU Make or similar, I would have had the option to express that build/, and rely on the tooling to rebuild those files if the ones upon which they depend are out of date.
I've seen that there are a number of gulp-<something about inlining> plugins, but none of them make clear whether they support this conditional recompilation by watching paths that were imported for changes (I doubt it).
Given my background in systems programming, I may well be approaching Javascript build tooling in a completely incorrect way.
Note: This question is only relevant for Grunt 0.3.x and has been left for reference. For help with the latest Grunt 1.x release please see my comment below this question.
I'm currently trying to use Grunt.js to setup an automatic build process for first concatenating and then minifying CSS and JavaScript files.
I have been able to successfully concatenate and minify my JavaScript files, although each time I run grunt it seems to just append to the file instead of overwriting them.
As for the minifying or even concatenating CSS, I have been unable to do this as of yet!
In terms of grunt CSS modules I have tried using consolidate-css, grunt-css & cssmin but to no avail. Could not get my head around how to use them!
My directory structure is as follows (being a typical node.js application):
app.js
grunt.js
/public/index.html
/public/css/[various css files]
/public/js/[various javascript files]
Here is what my grunt.js file currently looks like in the root folder of my application:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:package.json>',
concat: {
dist: {
src: 'public/js/*.js',
dest: 'public/js/concat.js'
}
},
min: {
dist: {
src: 'public/js/concat.js',
dest: 'public/js/concat.min.js'
}
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true
},
globals: {
exports: true,
module: false
}
},
uglify: {}
});
// Default task.
grunt.registerTask('default', 'concat min');
};
So just to summarise I need help with two questions:
How to concatenate and minify all my css files under the folder /public/css/ into one file, say main.min.css
Why does grunt.js keep on appending to the concatenated and minified javascript files concat.js and concat.min.js under /public/js/ instead of overwriting them each time the command grunt is run?
Updated 5th of July 2016 - Upgrading from Grunt 0.3.x to Grunt 0.4.x or 1.x
Grunt.js has moved to a new structure in Grunt 0.4.x (the file is now called Gruntfile.js). Please see my open source project Grunt.js Skeleton for help with setting up a build process for Grunt 1.x.
Moving from Grunt 0.4.x to Grunt 1.x should not introduce many major changes.
concat.js is being included in the concat task's source files public/js/*.js. You could have a task that removes concat.js (if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.
If doing the latter, you could put all your sources under ./src and your built files under ./dest
src
├── css
│ ├── 1.css
│ ├── 2.css
│ └── 3.css
└── js
├── 1.js
├── 2.js
└── 3.js
Then set up your concat task
concat: {
js: {
src: 'src/js/*.js',
dest: 'dest/js/concat.js'
},
css: {
src: 'src/css/*.css',
dest: 'dest/css/concat.css'
}
},
Your min task
min: {
js: {
src: 'dest/js/concat.js',
dest: 'dest/js/concat.min.js'
}
},
The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file
grunt.loadNpmTasks('grunt-css');
And then set it up
cssmin: {
css:{
src: 'dest/css/concat.css',
dest: 'dest/css/concat.min.css'
}
}
Notice that the usage is similar to the built-in min.
Change your default task to
grunt.registerTask('default', 'concat min cssmin');
Now, running grunt will produce the results you want.
dest
├── css
│ ├── concat.css
│ └── concat.min.css
└── js
├── concat.js
└── concat.min.js
I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.
Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.
For all those interested in concatenation with the requirejs optimizer, check out this post
Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS
I agree with above answer. But here is another way of CSS compression.
You can concat your CSS by using YUI compressor:
module.exports = function(grunt) {
var exec = require('child_process').exec;
grunt.registerTask('cssmin', function() {
var cmd = 'java -jar -Xss2048k '
+ __dirname + '/../yuicompressor-2.4.7.jar --type css '
+ grunt.template.process('/css/style.css') + ' -o '
+ grunt.template.process('/css/style.min.css')
exec(cmd, function(err, stdout, stderr) {
if(err) throw err;
});
});
};
You don't need to add the concat package, you can do this via cssmin like this:
cssmin : {
options: {
keepSpecialComments: 0
},
minify : {
expand : true,
cwd : '/library/css',
src : ['*.css', '!*.min.css'],
dest : '/library/css',
ext : '.min.css'
},
combine : {
files: {
'/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
}
}
}
And for js, use uglify like this:
uglify: {
my_target: {
files: {
'/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
}
}
}
I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:
https://stackoverflow.com/a/33481683/1897196