How to use npm with ASP.NET Core

前端 未结 10 2033
孤街浪徒
孤街浪徒 2020-11-29 15:05

I\'m using npm to manage the jQuery, Bootstrap, Font Awesome and similar client libraries I need for my ASP.NET Core application.

The approach that worked for me sta

10条回答
  •  臣服心动
    2020-11-29 15:59

    By publishing your whole node_modules folder you are deploying far more files than you will actually need in production.

    Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.

    You can then also completely remove the FileServer configuration and rely on UseStaticFiles instead.

    Currently, gulp is the VS task runner of choice. Add a gulpfile.js to the root of your project, and configure it to process your static files on publish.

    For example, you can add the following scripts section to your project.json:

     "scripts": {
        "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
      },
    

    Which would work with the following gulpfile (the default when scaffolding with yo):

    /// 
    "use strict";
    
    var gulp = require("gulp"),
        rimraf = require("rimraf"),
        concat = require("gulp-concat"),
        cssmin = require("gulp-cssmin"),
        uglify = require("gulp-uglify");
    
    var webroot = "./wwwroot/";
    
    var paths = {
        js: webroot + "js/**/*.js",
        minJs: webroot + "js/**/*.min.js",
        css: webroot + "css/**/*.css",
        minCss: webroot + "css/**/*.min.css",
        concatJsDest: webroot + "js/site.min.js",
        concatCssDest: webroot + "css/site.min.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"]);
    

提交回复
热议问题