5

I have created a new dotnet core project using yeoman in osx. So, It didn't have package.json and gulpfile.js. I've added them manually

I have delete main.css & main.min.css file ./wwwroot/css because I'm writing all my styles in scss so it would automatically generate .css files

But, in this case nothing happens. No .css get generated & scss styles doesn't works

When build my project & run it with dotnet run command after editing sass file nothing happens. No css file gets generated

./wwwroot/styles/scss/main2.scss

$base: #CC0000;
body {
    background-color: $base;
}

package.json

{
    "devDependencies": {
        "gulp": "3.8.11",
        "gulp-concat": "2.5.2",
        "gulp-cssmin": "0.1.7",
        "gulp-uglify": "1.2.0",
        "rimraf": "2.2.8",
        "gulp-sass": "1.3.3"
    }
}

gulpfile.js

/// <binding Clean='clean' />
"use strict";

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass");

var paths = {
    webroot: "./wwwroot/"
};

paths.js = paths.webroot + "js/*.js";
paths.minJs = paths.webroot + "js/*.min.js";
paths.css = paths.webroot + "css/*.css";
paths.minCss = paths.webroot + "css/*.min.css";
paths.concatJsDest = paths.webroot + "js/site.min.js";
paths.concatCssDest = paths.webroot + "css/site.min.css";

gulp.task("sass", function() {
    return gulp.src("./wwwroot/styles/scss/main2.scss")
        .pipe(sass())
        .pipe(gulp.dest(project.webroot + '/css'));
});

gulp.task("clean:js", function(cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function(cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("min:js", function() {
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.concatJsDest))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function() {
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.concatCssDest))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("min", ["min:js", "min:css"]);

project.json

{
    "dependencies": {
        "Microsoft.NETCore.App": {
            "version": "1.1.0",
            "type": "platform"
        },
        "Microsoft.AspNetCore.Diagnostics": "1.1.0",
        "Microsoft.AspNetCore.Mvc": "1.1.0",
        "Microsoft.AspNetCore.Razor.Tools": {
            "version": "1.1.0-preview4-final",
            "type": "build"
        },
        "Microsoft.AspNetCore.Routing": "1.1.0",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
        "Microsoft.AspNetCore.StaticFiles": "1.1.0",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.Configuration.CommandLine": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.Extensions.Logging.Debug": "1.1.0",
        "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
        "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0"
    },

    "tools": {
        "BundlerMinifier.Core": "2.2.306",
        "Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final",
        "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final"
    },

    "frameworks": {
        "netcoreapp1.1": {
            "imports": [
                "dotnet5.6",
                "portable-net45+win8"
            ]
        }
    },

    "buildOptions": {
        "emitEntryPoint": true,
        "preserveCompilationContext": true
    },

    "runtimeOptions": {
        "configProperties": {
            "System.GC.Server": true
        }
    },

    "publishOptions": {
        "include": [
            "wwwroot",
            "**/*.cshtml",
            "appsettings.json",
            "web.config"
        ]
    },

    "scripts": {
        "precompile": ["dotnet bundle"],
        "prepublish": [
            "npm install",
            "bowser install",
            "gulp clean",
            "gulp min"
        ],
        "postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"],
        "prebuild": "gulp sass",
        "postbuild": "echo after building",
        "prepack": "echo before packing",
        "postpack": "echo after packing",
        "prerestore": "echo before restoring packages",
        "postrestore": "echo after restoring packages"
    },

    "tooling": {
        "defaultNamespace": "Sample"
    }
}

after changing "precompile": ["gulp sass"]

$ 

dotnet run
Project Sample (.NETCoreApp,Version=v1.1) will be compiled because project is not safe for incremental compilation. U
se --build-profile flag for more information.
Compiling Sample for .NETCoreApp,Version=v1.1
[08:50:23] Warning: gulp version mismatch:
[08:50:23] Global gulp is 3.9.1
[08:50:23] Local gulp is 3.8.11
[08:50:23] Using gulpfile ~/Unity3D/DotNetCore/Sample/gulpfile.js
[08:50:23] Starting 'sass'...
[08:50:23] Finished 'sass' after 19 ms

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

2 Answers 2

4

Please try the following 2 ideas:

  1. Add a "precompile" script to the scripts section of your project.json file which invokes the gulp sass task:

    "precompile": ["gulp sass"]
    
  2. Change your gulp sass task to the following:

    gulp.task("sass", function() {
         return gulp.src("./wwwroot/styles/scss/main2.scss")
             .pipe(sass())
             .pipe(gulp.dest(paths.webroot + '/css'));
    });
    

The task currently references a variable named project, which doesn't exist.

Also, to fix the gulp version mismatch warning, run the following from a command shell from the directory in which your package.json file lives: npm i -D [email protected]

Alternatively, you could just change the 3.8.11 version number for gulp in your package.json file to 3.9.1.

Sign up to request clarification or add additional context in comments.

Comments

2

I solved this issue from another angle as I was unable to get the above running with a dotnetcore 2.0 application.

Initially I tried the recommended approach from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1 and convert the project.json file with the changes suggested by @Scott Addie into an XML syntax supported in the csproj file. Looks something like this:

<Target Name="MyPreCompileTarget" BeforeTargets="Build">
    <Exec Command="gulp frontend" ContinueOnError="false" />
</Target>

But, depending on the logic inside your gulpfile.js, this sometimes refused to run. In my case it seemed to fail on filewatchers like this one:

gulp.watch('./frontend/source/javascript/**/*.js', ['compileJs']);

So I ended up apporaching it the other way around. Start the sass compilation tool from my gulpfile.js and then from within the gulpfile.js start the dotnet process. Something like this:

/**
 * NodeJS Gulp tasks for "compiling" frontend files and start potentially start the dotnetcore application
 */

const gulp = require('gulp');
const plumber = require('gulp-plumber');
const sass = require('gulp-sass');
const runSequence = require('run-sequence').use(gulp);
const minifyCss = require('gulp-minify-css');
const notifier = require('node-notifier');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const sourcemaps = require('gulp-sourcemaps');
const path = require('path');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const livereload = require('gulp-livereload');
var spawn = require('child_process').spawn;
var fancyLog = require('fancy-log');
var beeper = require('beeper');

// Port that livereload is listening to
const liveReloadPort = 5812;

/**
 * Initialize the basic tasks for compiling front-end assets
 */
gulp.task('frontend', function () {
    return runSequence(
        'compileJs',
        'compileSass',
        'watch',
        'livereload')
})

/**
 * Initialize tasks for compiling front-end assets and runs dotnet in watch mode as well
 */
gulp.task('dotnet', function () {
    return runSequence(
        'compileJs',
        'compileSass',
        'watch',
        'livereload',
        function () {

            //
            // Start the dotnet core process
            //
            const child = spawn("dotnet", ["watch", "run"], {
                    cwd: process.cwd()
            })
            let stdout = '';
            let stderr = '';

            child.stdout.setEncoding('utf8');

            child.stdout.on('data', function (data) {
                stdout += data;
                console.log(data);
            });

            child.stderr.setEncoding('utf8');
            child.stderr.on('data', function (data) {
                stderr += data;
                fancyLog.error(data);
                beeper();
            });

            child.on('close', function (code) {
                fancyLog("Done with exit code", code);
                fancyLog("You access complete stdout and stderr from here"); // stdout, stderr
            });

        });
})

/**
 * Starts the livereload tool
 */
gulp.task('livereload', function () {
    // Start livereload
    console.log('* Starting livereload on port: ' + liveReloadPort);
    livereload.listen(5812);
})

/**
 * Watches the filesystem and initializes the tasks when a file has been changed
 */
gulp.task('watch', function () {

    // 1) Compile the client-side JavaScript file when one of the source files changes
    gulp.watch('./frontend/source/javascript/**/*.js', ['compileJs']);

    // 2) Compile the client-side CSS file when one of the source SASS files changes
    gulp.watch('./frontend/source/stylesheets/*.scss', ['compileSass']);
});

/**
 * Compiles SASS files and stores the result into the public folder
 */
gulp.task('compileSass', function () {

    return gulp.src('./frontend/source/stylesheets/main.scss')
        .pipe(plumber())
        .pipe(sass().on('error', function (err) {
            console.log('SASS compile error: ', err.toString());

            notifier.notify({
                'title': 'SASS Compile Error',
                'message': err.message
            });

            this.emit("end");
        }))
        .pipe(gulp.dest('./frontend/public/stylesheets'))

        .pipe(minifyCss({
            compatibility: 'ie8'
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./frontend/public/stylesheets'))
        .pipe(livereload());
});

/**
 * Compiles the Javascript files and stores the result in the public folder
 */
gulp.task('compileJs', function () {

    return browserify(path.resolve('./frontend/source/javascript', 'app.js'))
        .bundle()
        .on('error', function (err) {
            console.log('JS/Browserify error:', err.toString());

            notifier.notify({
                'title': 'JS Compile Error',
                'message': err.message
            });

            this.emit("end");
        })
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(gulp.dest('./frontend/public/javascript'))

        // Create minified version of JS
        .pipe(buffer())
        .pipe(uglify())
        .pipe(sourcemaps.init({
            loadMaps: true
        }))
        .pipe(sourcemaps.write('./maps'))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./frontend/public/javascript'))

        .pipe(livereload());
});

Now I can start my dotnetcore application with my frontend compilation tools using gulp dotnet

To be complete, this is my package.json file:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "..."
  },
  "author": "...",
  "license": "...",
  "homepage": "...",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babelify": "^8.0.0",
    "beeper": "^1.1.1",
    "browserify": "^16.2.2",
    "fancy-log": "^1.3.2",
    "gulp": "^3.9.1",
    "gulp-livereload": "^3.8.1",
    "gulp-minify-css": "^1.2.4",
    "gulp-plumber": "^1.2.0",
    "gulp-rename": "^1.2.3",
    "gulp-sass": "^4.0.1",
    "gulp-sourcemaps": "^2.6.4",
    "gulp-uglify": "^3.0.0",
    "node-notifier": "^5.2.1",
    "path": "^0.12.7",
    "run-sequence": "^2.2.1",
    "vinyl-buffer": "^1.0.1",
    "vinyl-source-stream": "^2.0.0",
    "webpack": "^4.10.2"
  },
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "es2015"
          ]
        }
      ]
    ]
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.