How to configure grunt file to minify JavaScript and CSS in .NET 6? - asp.net-core-mvc

I am new to grunt. Can anybody tell me how to configure grunt in .NET 6 MVC project?
I want that all the JavaScript files located at "wwwroot\lib\custom\js" folder should get minify and go at this location "wwwroot\js\minified\scripts"
I do not want to bundle everything into one file rather I am looking to minify these files separately like this:
Files at this location wwwroot\js\minified\scripts will look like below:
product.min.js
common-methods.min.js
I would also like to minify my CSS files and put at this "wwwroot\js\minified\css" location. I found this link helpful but somehow it is not working for me. Also that would be much helpful, if somebody can tell me how to configure "grunt-contrib-watch" as well?
Here is my package.json
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"grunt": "1.5.3",
"grunt-contrib-clean": "2.0.1",
"grunt-contrib-jshint": "3.2.0",
"grunt-contrib-concat": "2.1.0",
"grunt-contrib-uglify": "5.2.2",
"grunt-contrib-watch": "1.1.0"
}
}
and my gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
uglify: {
options: {
compress: true
},
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask("default", ["uglify"]);
}
Can anybody help me configure this?

Your gruntfile.js will look this
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
uglify: {
minifyJs: {
files: [{
expand: true,
cwd: 'wwwroot/lib/custom/js/',
src: ['**/*.js'],
dest: 'wwwroot/js/minified/scripts/',
ext: '.min.js',
extDot: 'first'
},],
},
},
cssmin: {
webStyles: {
files: [{
expand: true,
cwd: 'wwwroot/lib/custom/css/',
src: ['**/*.css'],
dest: 'wwwroot/js/minified/css/',
ext: '.min.css'
}]
}
},
watch: {
minifyJs: {
expand: true,
files: "wwwroot/lib/custom/js/**/*.js",
tasks: ["uglify:minifyJs"]
},
webStyles: {
expand: true,
files: "wwwroot/lib/custom/css/**/*.css",
tasks: ["cssmin:webStyles"]
},
options: {
spawn: false,
event: ['all']
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask("default", ["watch"]);
}
You can refer the documentation for more information.

Related

Async await doesn't get compiled in Grunt

I am trying to compile my ES6+ code to vanilla js using Grunt task runner.
I have purposely chosen Grunt over webpack and gulp because I just wanted to minify my js files.
I have successfully compiled my ES6 code to vanilla after running the code got an error saying generatorRuntime is not defined. After analysing the issue I could that my async and await code is giving the issue after it gets converted to vanilla js.
I have my code snippet of my gruntfile.js and package.json.
babel: {
options: {
sourceMap: true
},
dist: {
files: [{
"expand": true,
"cwd": "./htdocs/js/src",
"src": ["**/*.js"],
"dest": "./htdocs/js/compiled/",
"ext": ".js"
}]
}
},
//uglify will minify all the js files in js/src folder.
uglify: {
all_src : {
options : {
sourceMap : true
},
files: [{
expand: true,
flatten: true,
cwd:'./htdocs/js/compiled',
src: '**/*.js',
dest: './htdocs/js/dist',
ext: '.min.js'
}]
}
}
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-contrib-uglify');
Package.json
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-latest": "^6.24.1",
"grunt": "^1.1.0",
"grunt-babel": "^7.0.0",
"grunt-cli": "^1.3.2",
"grunt-contrib-uglify": "^4.0.1"
},
"babel": {
"presets": [
"latest"
]
}
That's probably because the polyfills aren't getting shipped in your bundle. In your babel.options object inside Gruntfile, you can set
presets: [['#babel/preset-env', { useBuiltIns: 'usage', corejs: 3 }]]
and don't forget to include corejs as dependency in your project.
npm install core-js --save

Can't compile Sass with Grunt

I'm new to Grunt and am following this tutorial.
I'm having a heck of a time trying to get Grunt to compile Sass. I keep getting the following when I run grunt sass:
Loading "sass.js" tasks...ERROR
>> SyntaxError: Unexpected token (
Warning: Task "sass" not found. Use --force to continue.
Aborted due to warnings.
node: v6.11.0,
npm: v6.4.1,
grunt cli: v1.3.2
package.json:
{
"name": "yb",
"version": "1.0.0",
"description": "yb site build",
"main": "src/js/main.js",
"dependencies": {},
"devDependencies": {
"grunt": "^1.0.3",
"grunt-contrib-concat": "^1.0.1",
"grunt-sass": "^3.0.2",
"node-sass": "^4.10.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Scott",
"license": "ISC"
}
Gruntfile.js
module.exports = function(grunt) {
// Configuration
grunt.initConfig({
concat: {
js: {
src: ['src/**/*.js'],
dest: 'assets/js/main.js'
},
css: {
src: ['src/**/*.css'],
dest: 'assets/css/main.css'
}
},
sass: {
build: {
files: [{
src: 'src/sass/test.scss',
dest: 'assets/css/test.css'
}]
}
}
});
// Load Plugins
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-sass');
// Register Tasks
grunt.registerTask('concat-js', ['concat:js']);
grunt.registerTask('concat-css', ['concat:css']);
};
The grunt-sass docs give a different configuration (which I've also tried), but I still can't get it to compile.
As far as I know, everything is installed. I can't find where I'm going off the rails here. Any thoughts?
check ruby with ruby -v (install [ruby][1] )
Install Sass with sudo gem install sass (install [sass][2] )
setting for Grunt Tasks & run grunt convert-sass
// Load Grunt
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Tasks
concat: {
js: {
src: ['src/**/*.js'],
dest: 'assets/js/main.js'
},
css: {
src: ['src/**/*.css'],
dest: 'assets/css/main.css'
}
},
sass: {
dist: {
options: {
sourcemap: 'none'
},
files: [{
expand: true,
cwd: 'src/sass',
src: ['**/*.scss'],
dest: 'assets/css',
ext: '.css'
}]
}
}
});
// Load plugins
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-concat');
// Register Tasks
grunt.registerTask('concat-js', ['concat:js']);
grunt.registerTask('concat-css', ['concat:css']);
grunt.registerTask('convert-sass', 'sass');
};

Webpack sass to css specify a specific folder?

I've been looking over the docs and checking other people's questions but I can't find the simple answer to how to compile all my sass down to a simple css file and specify the directory I want the resulting css file to output to.
For quick context:
I have a public directory with a stylesheets directory and a build directory in it. webpack compiles the app into build, and I'd like to have the sass compile style.css into the stylesheets directory.
Here's a screenshot of my public directory:
public dir img
I'd like to be able to do something like this in my webpack.config.js (only showing pertinent code for brevity):
const ExtractTextPlugin = require('extract-text-webpack-plugin');
...
// To be called in plugins:
const cssOutput = new ExtractTextPlugin('./public/stylesheets/style.css');
inside module loaders:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader'),
},
In plugins:
plugins: [
.
.
.
cssOutput,
],
I'd like to be able to access the output file with this line in my index.html file located in the public directory:
<link rel="stylesheet" href="/stylesheets/style.css" />
I'm currently doing this using gulp and it works fine, I'm just trying to transition everything into webpack. Any help would be greatly appreciated!
Turns out you can just set the output file like this:
const cssOutput = new ExtractTextPlugin('../stylesheets/style.css', { allChunks: true });
I made the noob mistake of forgetting to add:
require('_scss/style.scss');
in my index.jsx file.
For anyone who runs into this issue, I still had trouble with fonts and images, so inside module loaders in the webpack.config.js I had to add:
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
loader: 'file',
},
and since this output everything into my build directory, I just changed the css to output everything in the build directory as well to prevent path errors. I changed it to this:
const cssOutput = new ExtractTextPlugin('style.css', { allChunks: true });
Hopefully this helps someone else who runs into this type of issue!
Work for Me::
webpack.config.js
module.exports = {
entry: ['./src/app.ts', './src/sass/style.scss'],
module:{
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [path.resolve(__dirname, 'src', 'src/class')]
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '/css/[name].css'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader?-url'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
],
include: [path.resolve(__dirname, 'src/sass')]
}
]
},
output: {
filename: 'js/app.js',
path: path.resolve(__dirname, 'public')
}
}
postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {}
}
}
package.json
{
"name": "tsscript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"nov": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.5",
"css": "^3.0.0",
"css-loader": "^3.6.0",
"extract-loader": "^5.1.0",
"postcss-loader": "^3.0.0",
"sass": "^1.26.10",
"sass-loader": "^9.0.2",
"style-loader": "^1.2.1",
"ts-loader": "^8.0.0",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
Directory Snap:
Have you take a look at https://www.npmjs.com/package/extract-text-webpack-plugin?
you'll probably need it.
Recent solution, you can use mini-css-extract-plugin, css-loader, and sass-loader. mini-css-extract-plugin can create a CSS file per JS file which contains CSS.
Install dependencies:
npm i -D mini-css-extract-plugin css-loader sass-loader
For example, your main JS file that includes a style is ./src/index.js:
...
import './src/style.scss';
...
Configure webpack.config.js:
...
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
...
entry: {
main: './src/index.js',
},
plugins: [
new MiniCssExtractPlugin(),
],
...
module: {
rules: [
...
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
...
]
},
resolve: {
modules: ["node_modules", path.resolve(__dirname, "src")],
extensions: ['.js', '.scss', ...]
}
}
Then, you can check your output directory, there will be main.css. The plugin set default name to [name].css (entry name).

Watch whole folder for SASS changes with Grunt

I am trying to watch an entire folder for sass changes..
The directory is follows:
creatives/lp/folder/style.scss
creatives/lp/folder1/style.scss
And here is my grunt file
sass: {
dist: {
files: {
'creatives/lp/**/test.css' : 'creatives/lp/**/test.scss'
},
options: {
style: 'compressed',
},
}
},
Grunt is able to see sass changes but writes out the compiled CSS to:
creatives/lp/**/style.css
The CSS should be saved in the same folder as the source SCSS file...
your question is not so clear for me
- if you want multiple files to compile to one file with grunt you can make the files as array format
dist: {
files: [{
src: ['creatives/lp/folder/*.scss'],
dest: 'creatives/lp/folder/style.css',
}]
}
If you want the css file should be created in the same folder as scss file, you can use the following snippet.
sass: {
dist: {
options: {
style: 'compressed'
},
files: [{
expand: true,
cwd: 'creatives',
src: ['**/*.scss'],
dest:'creatives',
ext:'.css'
}]
}
}
I hope it solves your problem.

Syntax Error in Gruntfile.js - Sass Watch

I'm using grunt.js for the first time and I'm having trouble setting up a sass watch. I've successfully installed node.js and grunt and I was able to get it concatinating and minifying all my javascript files into one file. Then I moved onto trying to get it to watch and compile my sass files and I can't figure out why I keep getting this error in my command line (clearly there is a syntax error, but I don't know where it is?
here is my command line error:
Mandy at MandysMac in ~/Desktop/Dropbox/WEBSITES/Portfolio/wp-content/themes/mandy_made_this_theme on master*
$ grunt
/Users/Mandy/Desktop/Dropbox/WEBSITES/Portfolio/wp-content/themes/mandy_made_this_theme/Gruntfile.js:27
watch: {
^^^^^
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected identifier
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
Here is my package.json file:
{
"name": "mandy-made-this-theme",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-nodeunit": "~0.2.0",
"grunt-contrib-uglify": "~0.2.2",
"grunt-contrib-sass": "^0.7.3",
"grunt-contrib-watch": "^0.6.1"
}
}
And most importantly, Here is my grunt file:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: ['working/jquery-2.1.0.min.js, working/jquery-ui-1.10.4.custom.min.js', 'working/jquery.smooth-scroll.min.js', 'working/isotope.pkgd.min.js', 'working/scripts.js'], //input
dest: 'scripts/build/scripts.min.js' //output
}
},
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
'style.css': 'sass/style.scss'
}
}
}
watch: {
css: {
files: '**/*.scss',
tasks: ['sass'],
options: {
livereload: true,
}
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task(s).
grunt.registerTask('default',['uglify', 'sass', 'watch']);
}
You are missing a comma after sass object
'style.css': 'sass/style.scss'
}
}
}, // added , here
watch: {
css: {
files: '**/*.scss',

Resources