search
HomeWeb Front-endJS TutorialUse Node.js-based build tool Grunt to publish ASP.NET MVC projects_node.js

Grunt Introduction
Grunt is a construction tool based on js and node.js. Since node.js has become more and more popular during this period, grunt has rich open source community support and has produced many plug-ins. There are also some plugins scattered in the node community. Construction is a broad expression. The traditional understanding is compilation, packaging, and copying. Now, as the technology becomes more and more abundant, construction also includes the preprocessing of front-end components, such as preprocessing of sass and less into css, css, and js. Compression and merging. The grunt plug-in can support these new building concepts very well, and is more suitable for projects built with open source technologies. Although Grunt is more used for program construction, in essence Grunt is a task running tool used to solve repetitive tasks.

Getting Started with Grunt
Install
Download and install Node.js. Download address

Check installation and view version:

node -v
v0.10.25

Install the grunt command line tool grunt-cli and use -g to install it globally, so that it can be used in any directory. The following command will add grunt to your system search path, so you can use this command in any directory.

npm install -g grunt-cli

It should be noted that under linux or mac, an error of no permissions will sometimes be reported. In this case, a sudo must be added in front

sudo npm install grunt-cli -g

View version:

grunt –version
grunt-cli v0.1.13

Uninstall. If you have previously installed Grunt globally, remove it first.

npm uninstall -g grunt

grunt-cli is just a grunt command line interface, which requires the use of grunt and its plug-ins. The grunt module itself must be installed in the project path (usually the project root directory), which requires the plug-in module. Whenever the grunt command is executed, it will look for the installed grunt locally through the nodejs require command. Because of this, you can run grunt commands in any subdirectory. If the cli finds a locally installed grunt, it will load the grunt library, apply the configuration you wrote in GruntFile, and then perform the corresponding tasks.

Configuration file
package.json
package.json is used to save the installed and required node modules in the current directory, for example:

{
 "name": "my-project-name",
 "version": "0.1.0",
 "author": "Your Name",

 "devDependencies": {
 "grunt": "~0.4.1"
 }
}

You can create this file manually or through the npm init command and follow the prompts to complete the creation of the package.json file. If you created the package.json manually, just download and install the required modules via npm install. When the module is installed, it will be saved in the node_modules directory.

If you want to add the required modules later, use the following command to update the package.json file synchronously

npm install <module> --save-dev

Gruntfile.js
The status of this file is just like a Makefile. It is a file that guides grunt to perform tasks. It needs to configure the parameters required by each plug-in module, load plug-ins, and define tasks. For more information about Gruntfile, please refer to here. It is recommended that readers have an overall understanding of Gruntfile before continuing.

Building ASP.NET MVC with Grunt
MSbuild
Before using grunt to build .NET projects, you must first understand MSbuild. MSBuild is Microsoft's tool for building programs. Currently, Visual Studio has fully used MSbuild to compile projects. MSbuild consists of a msbuild tool, a set of compiler or builder programs, and xml files. In fact, the .sln and .csproj project files in Visual Studio are xml that msbuild can recognize (hereinafter referred to as the msbuild configuration file). Visual Studio completes the build work by calling msbuild, and msbuild recognizes the parameters and build behavior identifiers. We can also call msbuild ourselves through the command line.

There are two key concepts in msbuild: Task and Property. Task is the entry point for msbuild to be executed directly as a target. When executing msbuild, it must point to the default Task, otherwise you must specify what the target Task is. Property is a variable. Just like variables in a program can affect program execution, Property can affect the behavior of the build.

The msbuild configuration file generated by VisualStudio is actually very complicated. On the surface, there are only a few uplinks. However, it imports some predefined configuration files into the current file through import, making it impossible to fully view the complete configuration file. Find the key Task item. Fortunately, there is a tool that can be used to help analyze the structure of the msbuild configuration file.

In addition, when calling msbuild, you can override the default properties and tasks through command line parameters. For example, the following call indicates that the "Rebuild" Task is used as the target and the Configuration attribute is set to Debug:

msbuild ConsoleApplication1.csproj /target:Rebuild /property:Configuration=Debug

更多关于msbuild,请参考微软的文档

手动使用msbuild代替VisualStudio
以发布到本机为例,经过笔者在VS2012下的环境中测试,使用VS在调用msbuild时使用了如下关键的参数覆盖:

  • Configuration:Debug或者Release,相信使用VS的同学对此不会陌生
  • VisualStudioVersion:VS在安装的时候会将一些公用的,VisualStudio相关的,msbuild配置文件预先存在某个版本相关的地方,在VisualStudio生成项目文件时,会包含一个$VisualStudioVersion变量,这个变量会与路径结合指向这些预先准备好的配置文件。在2012下,需要将这个值设置为11.0
  • WarningLevel:编译时的告警级别
  • DeleteExistingFiles:发布功能使用到的是否删除已存在文件的选项
  • WebPublishMethod:发布方式,笔者常用的是FileSystem,即发布到本机或远程共享的某个目录
  • publishUrl:如果WebPublishMethod是FileSystem,这个值表示发布的磁盘路径

关键的任务:

  • Build:即VS中针对某个项目的编译功能
  • Rebuild:即VS中针对某个项目的重新编译功能
  • WebPublish:即VS针对某个项目的发布功能

至此,我们已经可以使用msbuild命令行来代替VS的一些构建动作了。由于本篇的重点是grunt,读者可以参见微软的说明,自己试验一下:

PS: MSbuild通常位于类似这样的目录下:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe
使用grunt-msbuild调用msbuild
终于到了介绍本文的主角了:grunt-msbuild。这是一个个人开发的msbuild调用中间件。作为grunt的插件,经过笔者亲测,完全可以使用。结合其他的grunt插件,简化了笔者发布项目的过程。

你可以像下面这样将这个插件添加进项目的Gruntfile,实现自动发布:

msbuild: {
  fontend: {    
    src: ['Web.FontEnd/Web.FontEnd.csproj'],
    options: {
      projectConfiguration: 'Release',
      targets: ['WebPublish'],
      stdout: true,
      maxCpuCount: 4,
      buildParameters: {
        WarningLevel: 2,
  VisualStudioVersion: "11.0",
  DeleteExistingFiles: 'True',
  WebPublishMethod: 'FileSystem',
  publishUrl: [font_pwd]
      },
      verbosity: 'quiet'
    }
  }
}

上面的代码实现了,将Web.FontEnd.csproj项目在Release模式下通过FileSystem发布方式发布到font_pwd变量指代的目录下。 这里需要注意的是,可能需要根据自己的VS版本修改VisualStudioVersion参数,可以通过查看类似如下目录:C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0来检查。font_pwd是一个js变量,根据需要进行调整。

Grunt的完整配置就不给出了,主要是要知道这几个关键的参数设置。

在实际使用过程中DeleteExistingFiles这个参数似乎不起作用,所以可能需要另外再包含清空目标文件夹的任务。下面是实际任务运行时的部分截图:

2016215152103887.jpg (542×315)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software