如何从scss文件dotnet核心生成css文件

时间:2017-02-03 02:15:20

标签: sass gulp asp.net-core-mvc asp.net-core-1.0

我在osx中​​使用yeoman创建了一个新的dotnet核心项目。所以,它没有package.json和gulpfile.js。我手动添加了它们

我删除了main.css& main.min.css文件./wwwroot/css因为我在scss中编写了所有样式所以它会自动生成.css文件

但是,在这种情况下没有任何反应。没有.css生成& scss样式不起作用

构建我的项目&编辑sass文件后,用dotnet run命令运行它没有任何反应。没有生成css文件

./的wwwroot /风格/ 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"
    }
}

更改&#34;预编译&#34;:[&#34; gulp sass&#34;]

$ 

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 个答案:

答案 0 :(得分:3)

请尝试以下两个想法:

  1. 添加&#34;预编译&#34; project.json 文件的 scripts 部分的脚本,该文件调用gulp sass 任务:

    "precompile": ["gulp sass"]
    
  2. 将您的gulp sass 任务更改为以下内容:

    gulp.task("sass", function() {
         return gulp.src("./wwwroot/styles/scss/main2.scss")
             .pipe(sass())
             .pipe(gulp.dest(paths.webroot + '/css'));
    });
    
  3. 该任务当前引用了一个名为 project 的变量,该变量不存在。

    另外,要修复gulp版本不匹配警告,请从package.json文件所在目录中的命令shell运行以下命令: npm i -D gulp@3.9.1

    或者,您可以将package.json文件中的gulp的3.8.11版本号更改为3.9.1。

答案 1 :(得分:2)

我从另一个角度解决了这个问题,因为我无法使用dotnetcore 2.0应用程序运行上述内容。

最初我尝试了Microsoft推荐的方法:https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1并将project.json文件与@Scott Addie建议的更改转换为csproj文件支持的XML语法。看起来像这样:

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

但是,根据gulpfile.js中的逻辑,这有时会拒绝运行。在我看来,它似乎在像这样的文件管理器上失败了:

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

所以我最后以相反的方式来推销它。从我的gulpfile.js启动sass编译工具,然后从gulpfile.js中启动dotnet进程。像这样:

/**
 * 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());
});

现在我可以使用gulp dotnet

使用我的前端编译工具启动我的dotnetcore应用程序

要完成,这是我的package.json文件:

{
  "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"
          ]
        }
      ]
    ]
  }
}