【问题标题】:how to generate css file from scss file dotnet core如何从 scss 文件 dotnet core 生成 css 文件
【发布时间】:2017-02-03 02:15:20
【问题描述】:

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

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

但是,在这种情况下,什么都没有发生。没有 .css 生成 & scss 样式不起作用

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

./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"
    }
}

更改“预编译”后:[“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)

【问题讨论】:

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


    【解决方案1】:

    请尝试以下 2 个想法:

    1. 将“预编译”脚本添加到 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'));
      });
      

    任务当前引用了一个名为 project 的变量,该变量不存在。

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

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

    【讨论】:

      【解决方案2】:

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

      最初,我尝试了 Microsoft 推荐的方法:https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1,并将带有 @Scott Addie 建议的更改的 project.json 文件转换为 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"
                ]
              }
            ]
          ]
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-18
        • 2023-01-30
        • 1970-01-01
        • 2016-06-30
        • 2019-07-21
        • 1970-01-01
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多