简体   繁体   English

如何阻止ASP.NET Core 2.0 MVC缩小修改特定文件?

[英]How can I stop ASP.NET Core 2.0 MVC minification from modifying a specific file?

I'm performing Bundling and Minification in ASP.NET Core 2.0 MVC and I've run into an issue with the minification taking place when it shouldn't. 在ASP.NET Core 2.0 MVC中执行Bundling和Minification,但是当它不应该发生缩小时我遇到了一个问题。 In my page I have the following script tag: 在我的页面中,我有以下脚本标记:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT"
        crossorigin="anonymous"
        asp-fallback-test="window.jQuery"
        asp-fallback-src="~/js/jquery.min.js">
</script>

In my bundleconfig.json I have the following section: 在我的bundleconfig.json中,我有以下部分:

{
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
        "node_modules/jquery/dist/jquery.min.js"
    ],
    "minify": {
        "enabled": false
    }
}

The problem is that the ~/js/jquery.min.js file is losing its trailing newline character when it's transformed by this bundling/minification process which makes the expected hash of the file no longer match. 问题是〜/ js / jquery.min.js文件在通过此捆绑/缩小过程转换时丢失其尾随换行符,这使得文件的预期散列不再匹配。 As a workaround I can specify 2 hashes for the integrity value to support a file with or without the newline like so: 作为一种解决方法,我可以为完整性值指定2个哈希,以支持包含或不包含换行符的文件,如下所示:

integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT sha384-I7/UTpkJas2maMjJpGmrvEgQecqO8Dta/9Wwh+cQrH6Jj984WRRFhWg4MV/oTkIW"

But that's less efficient than just making sure the minification doesn't touch this file. 但这不仅仅是确保缩小不会触及此文件。 How can I stop this newline from being trimmed? 如何阻止这条新线被修剪?

Try with following configuration : 尝试以下配置:

//1. by default outputMode is singleLine which removes new lines and output on a single line. We are setting it to none.
{
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
        "node_modules/jquery/dist/jquery.min.js"
     ],
     "minify": {
           "enabled": false,
            outputMode: "none"         
      }
}


//Alternatively, outputMode = "multipleLines" should work with a indentSize of 0 as well.
//In this mode , output file has each line indented by specified indentSize
{
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
        "node_modules/jquery/dist/jquery.min.js"
     ],
      "minify": {
       "enabled": false,
        outputMode: "multipleLines",
         indentSize: 0
    }
}

You can read about available settings for javascript minifier here 您可以在此处阅读有关javascript minifier的可用设置

I find the default minification system somewhat limited and for things like excluding files I usually end up using a task runner like Gulp instead. 我发现默认的缩小系统有些限制,对于排除文件之类的东西,我通常最终会使用像Gulp这样的任务运行器。

So here is how to do what you want using gulp: 所以这里是如何使用gulp做你想要的:

Adding npm support 添加npm支持

First add support for npm packages by adding a package.json file if you don't already have it, inside the solution explorer, right click on your project name, then, add new item and search for npm configuration file . 首先通过添加package.json文件添加对npm包的支持(如果您还没有),在解决方案资源管理器中,右键单击项目名称,然后添加新项并搜索npm配置文件

Inside package.json add the following required gulp dependencies as well as any other client side library you want to use, for example, jquery, bootstrap, etc.: 在package.json中添加以下必需的gulp依赖项以及您要使用的任何其他客户端库,例如,jquery,bootstrap等:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "gulp": "3.9.1",
    "gulp-concat": "2.6.1",
    "gulp-cssmin": "0.2.0",
    "gulp-uglify": "3.0.0",
    "gulp-filter": "5.1.0",
    "gulp-watch": "5.0.0",
    "rimraf": "2.6.2",
    "jquery": "3.3.1",
    "bootstrap": "4.1.1",
    "popper.js": "1.14.3"
  }
}

Once you save the file a folder will be added to your project directory called node_modules (this folder is not visible unless you activate "Show all files" on the Solution Explorer toolbar. 保存文件后,文件夹将添加到名为node_modules的项目目录中(除非您在解决方案资源管理器工具栏上激活“显示所有文件”,否则此文件夹不可见。

This folder contains all the libraries and their dependencies, we will use gulp to copy the libraries you want to include from node_modules to your wwwroot folder. 此文件夹包含所有库及其依赖项,我们将使用gulp将要包含的库从node_modules复制到wwwroot文件夹。

Setting up Gulp 设置Gulp

  • Create two other folders in the root of your project, name one Styles and the other one Scripts . 在项目的根目录中创建另外两个文件夹,命名一个样式 ,另一个命名为Scripts

You can use these folders for your application scripts and style-sheets, we will use gulp to combine, minify and copy to the wwwroot folder all these resources. 您可以将这些文件夹用于应用程序脚本和样式表,我们将使用gulp将所有这些资源组合,缩小并复制到wwwroot文件夹。

The idea is to avoid using the wwwroot folder directly so you have full control of what you expose and how when you publish your Website. 我们的想法是避免直接使用wwwroot文件夹,这样您就可以完全控制自己公开的内容以及发布网站的方式。

  • Add a javascript file to the root of your project and name it gulpfile.js 将javascript文件添加到项目的根目录并将其命名为gulpfile.js

You can use gulp to create different tasks that can be executed automatically before or after build, when cleaning the project, when the project is open in Visual Studio, etc... 您可以使用gulp创建可在构建之前或之后,清洁项目,在Visual Studio中打开项目等时自动执行的不同任务...

For this example I will create the following tasks: 在本例中,我将创建以下任务:

  • clean:js to clear all files in your wwwroot/js folder. clean:js清除wwwroot / js文件夹中的所有文件。
  • clean:css to clear all css files in your wwwroot/css folder. clean:css清除wwwroot / css文件夹中的所有css文件。
  • clean to run clean:js and clean:css one after the other. 干净运行干净:js和清洁:css一个接一个。
  • watch to watch for changes in your application and stylesheet files so whenever you save them, the resources are regenerated in wwwroot. 注意观察应用程序和样式表文件的变化,以便在保存时,资源在wwwroot中重新生成。
  • dev:js to generate wwwroot javascript resources during development. dev:js在开发过程中生成wwwroot javascript资源。
  • dev:css to generate wwwroot css resources during development. dev:css在开发期间生成wwwroot css资源。
  • dev to execute dev:js and dev:css one after the other. dev一个接一个地执行dev:js和dev:css。
  • min:js to generate wwwroot javascript resources during production. min:js在生产期间生成wwwroot javascript资源。
  • min:css to generate wwwroot css resources during production. min:css在生产期间生成wwwroot css资源。
  • min to execute min:js and min:css one after the other. min执行min:js和min:css一个接一个。

Gulp has a lot of plugins, you need to specify which ones are required for your project, to do that, add the following at the beginning of your script: Gulp有很多插件,您需要指定项目所需的插件,为此,在脚本的开头添加以下内容:

/// <binding BeforeBuild='clean, dev, min' Clean='clean' ProjectOpened='watch' />
"use strict";

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

As you may deduct from the name, the gulp-filter plugin is what we will use to exclude files from the minification process. 正如您可以从名称中扣除的那样,我们将使用gulp-filter插件从缩小过程中排除文件。

Now, you need to set up some general paths: 现在,您需要设置一些通用路径:

var paths = {
    webroot: "./wwwroot/",
    scripts: "./Scripts/",
    styles: "./Styles/",
    node_modules: "./node_modules/"
};

//The following paths will be used to look for any js and css file in your Script and Styles folder or any subfolder inside them 
paths.scripts = paths.scripts + "**/*.js";
paths.styles = paths.styles + "**/*.css";

Note: if you need to specify the order of any script inside these folders, you can do as follows: 注意:如果您需要指定这些文件夹中任何脚本的顺序,您可以执行以下操作:

paths.scripts = [paths.scripts + "/somescript.js", paths.scripts + "**/*.js"];
paths.styles = [paths.styles + "/somecss.css", paths.styles + "**/*.css"];

Next, define the paths to the vendor scripts which are inside the node_modules folder: 接下来,定义node_modules文件夹中供应商脚本的路径:

paths.vendorJs = [paths.node_modules + "jquery/dist/jquery.js", 
        paths.node_modules + "popper.js/dist/umd/popper.js",
            paths.node_modules + "bootstrap/dist/js/bootstrap.js"];

paths.vendorCss = [paths.node_modules + "bootstrap/dist/css/bootstrap.css"];

paths.minVendorJs = [paths.node_modules + "jquery/dist/jquery.min.js", 
    paths.node_modules + "jquery/dist/umd/popper.min.js", 
      paths.node_modules + "bootstrap/dist/js/bootstrap.min.js"];

paths.minVendorCss = [paths.node_modules + "bootstrap/dist/css/bootstrap.min.css"];

The idea is to avoid minification for any file that is specified in paths.minVendorJs as they are already minified. 我们的想法是避免缩小paths.minVendorJs指定的任何文件,因为它们已经缩小。 The following path will allow you to minify any specific vendor file if you need to do so: 如果需要,以下路径将允许您缩小任何特定供应商文件:

paths.vendorCssToMinify = [paths.node_modules + "perfect-scrollbar/css/perfect-scrollbar.css"]

Then, we define the output files that will be generated, for this example, only one script and one style-sheet will be generated that contains all the application files as well as all vendor files combined within them: 然后,我们定义将生成的输出文件,对于此示例,将只生成一个脚本和一个样式表,其中包含所有应用程序文件以及其中组合的所有供应商文件:

paths.concatJsDest = paths.webroot + "js/application.js";
paths.concatCssDest = paths.webroot + "css/application.css";

paths.minConcatJsDest = paths.webroot + "js/application.min.js";
paths.minConcatCssDest = paths.webroot + "css/application.min.css";

Finally, we define each task: 最后,我们定义每个任务:

gulp.task("clean:js", function (cb) {
    rimraf(paths.webroot + "js/**/*.js", cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.webroot + "css/**/*.css", cb);
});

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

gulp.task('watch', function () {
    gulp.watch(paths.styles, ['dev:css', 'clean:css']);
    gulp.watch(paths.scripts, ['dev:js', 'clean:js', ]);
});

gulp.task("dev:js", function () {
    return gulp.src(paths.vendorJs.concat(paths.scripts))
        .pipe(concat(paths.concatJsDest))
        .pipe(gulp.dest('.'));
});

gulp.task("dev:css", function () {
    return gulp.src(paths.vendorCss.concat(paths.styles))
        .pipe(concat(paths.concatCssDest))
        .pipe(gulp.dest('.'));
});

gulp.task("min:js", function () {
    // Files to skip from minification.
    var filter = gulpFilter(paths.minVendorJs, {
        restore: true
    });

    return gulp.src(paths.minVendorJs.concat(paths.scripts))
        .pipe(filter)
        .pipe(uglify())
        .pipe(filter.restore)
        .pipe(concat(paths.minConcatJsDest))
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function () {
    // Files to skip from minification.
    var filter = gulpFilter(paths.minVendorCss, {
        restore: true
    });
    return gulp.src(paths.minVendorCss.concat(paths.vendorCssToMinify).concat(paths.styles))
        .pipe(filter)
        .pipe(cssmin())
        .pipe(filter.restore)
        .pipe(concat(paths.minConcatCssDest))
        .pipe(gulp.dest("."));
});

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

And that's it! 就是这样!

To test the configuration, right click on your gulpfile.js file and select Task Runner Explorer . 要测试配置,请右键单击gulpfile.js文件并选择Task Runner Explorer If everything went correctly, you should see something like this: 如果一切正常,你应该看到这样的事情:

任务运行资源管理器

You can run the tasks by double clicking on them. 您可以通过双击来运行任务。

You can use the generated resources in your razor views like this: 您可以在剃刀视图中使用生成的资源,如下所示:

<environment include="Development">
    <link rel="stylesheet" href="~/css/application.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="~/css/application.min.css" />
</environment>

And

<environment include="Development">
    <script src="~/js/application.js"></script>
</environment>
<environment exclude="Development">
    <script src="~/js/application.min.js"></script>
</environment>

If you need to compile LESS or SASS files you need to use the corresponding Gulp plugin, see here for an example. 如果您需要编译LESS或SASS文件,则需要使用相应的Gulp插件,请参阅此处以获取示例。

More information about using Gulp in ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.0 有关在ASP.NET Core中使用Gulp的更多信息: https ://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view = aspnetcore-2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将配置值从Asp.Net Core MVC 2.0配置文件推送到React TypeScript客户端脚本? - How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script? ASP.NET Core 2.0 MVC 6.如何管理每个视图的javascript文件? - ASP.NET Core 2.0 MVC 6. How to manage javascript file for each view? 如何在ASP.NET MVC 4 Beta中禁用Javascript / CSS缩小 - How to disable Javascript/CSS minification in ASP.NET MVC 4 Beta Asp.Net MVC中JS和CSS的最小化 - minification Of JS And CSS In Asp.Net MVC ASP.NET MVC 4 JS Minification Error - ASP.NET MVC 4 JS Minification Error 如何在ASP.NET CORE MVC中导入一个js文件模块? - How to import a js file module in ASP.NET CORE MVC? 如何停止在页面加载时显示部分视图 - ASP.NET MVC - How can I stop showing a partial view on page load - ASP.NET MVC 如何将 Json 返回从 controller 发送到 Asp.NET Core MVC 应用程序的前端? - How can a Json return be sent from a controller to the frontend in Asp.NET Core MVC application? ASP.NET Core BundleMinifier 在缩小后删除异步修饰符 - ASP.NET Core BundleMinifier removes async modifier after minification ASP.NET MVC 4捆绑缩小确定但没有混淆 - ASP.NET MVC 4 bundles minification OK but there is NO obfuscation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM