preface

In the front-end development of the project, it is inevitable for most of my friends, including me, to use some third-party component packages in the project. At this point, we can’t control whether the team members choose to download the component directly from the official website, or simply search on the Internet and download it from some unknown source. At the same time, there may be dependencies between the components we add, and if we don’t download the references correctly, we may not be able to use them properly.

Therefore, how to download component packages from trusted sources, and how to easily resolve the dependencies between each component has become a problem we need to solve, so, is there a tool to help us solve this problem? Hello, yes, NPM.

Storage address: github.com/Lanesra712/…

Step by Step

In.net Framework projects, we can download and install front-end component packages in our projects through Nuget. But Nuget is more of a package manager for.net back-end projects, where managing front-end component packages is a bit out of place.

So, after.net Core came along, along with the development of the front end, Microsoft started recommending that we use Bower to manage the front end package in our project in the example project. Then, Bower is dead…

So here, I’m using NPM as the front-end package manager for our ASP.NET Core project.

1. Install Node environment

Node.js is an execution environment that can run Javascript on the server, which means that Javascript can be used not only on the front end, but also to build back-end services. NPM is the official package management tool provided by Node.js, so before using NPM, you need to install the Node.js environment on your computer.

Of course, if you’ve developed a front-end project like Vue or Angular before, you’ve already installed it. If not, go to the Node.js website (nodejs.org/en/download) and download the installation package based on the operating system you are using.

If you’re running Windows, it’s easy to download the MSI installation package and go next. In the latest node.js installation package, NPM is completed with the installation of Node.js. We can verify this by using the following command. When you can print out the version information you installed, the installation is complete.

//1. Node. js version node-v //2. NPM version NPM -vCopy the code

Use the NPM installation package

For the example project of this article, I use the MVC project generated by ASP.NET Core 2.2 by default. I have changed the solution in the process of writing this article.

When the sample project is created, bootstrap and jquery are automatically referenced in the project, so we try to manage our front-end package with NPM based on this project.

Right click on our project and add a package.json configuration file. This JSON file defines the various front-end modules needed for the project, along with the project’s configuration information (such as name, version, license, and so on). When we copy the project from elsewhere, the NPM install command will automatically download the front-end packages that need to be referenced in the project based on the configuration file.

For example, we need to add bootstrap and jquery to the project. If they are missing, our application will fail. Therefore, we need to add them to the Dependencies node. It will only be used for project development, so we just need to add it to devDependencies.

In the install command we added the –save modifier to add bootstrap to the Dependencies node. If you need to install the referenced package under the devDependencies node, use the –save-dev modifier.

npm install bootstrap --save
Copy the code

When you install jquery 1.9.1, NPM will prompt you to run the NPM audit command to check for possible security risks in the current project and suggestions on how to resolve them.

{
  "version": "1.0.0"."name": "aspnetcore.npm.tutorial"."private": true."devDependencies": {},
  "dependencies": {
    "bootstrap": "^ 4.3.1." "."jquery": "^ 3.4.1 track"."popper.js": "^ 1.14.7"}}Copy the code

When we execute the NPM install command for the first time, the system automatically creates the package-lock.json file for us, which records the specific source and version number of each NPM package actually installed in the current state. The package-lock.json file under the current project is as follows.

{
  "name": "aspnetcore.npm.tutorial"."version": "1.0.0"."lockfileVersion": 1."requires": true."dependencies": {
    "bootstrap": {
      "version": "This"."resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.3.1.tgz"."integrity": "sha512-rXqOmH1VilAt2DyPzluTi2blhk17bO7ef+zLLPlWvG494pDxcM234pJ8wTc/6R40UWizAIIMgxjvxZg5kmsbag=="
    },
    "jquery": {
      "version": "3.4.1 track."."resolved": "https://registry.npmjs.org/jquery/-/jquery-3.4.1.tgz"."integrity": "sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw=="
    },
    "popper.js": {
      "version": "1.14.7"."resolved": "https://registry.npmjs.org/popper.js/-/popper.js-1.14.7.tgz"."integrity": "sha512-4q1hNvoUre/8srWsH7hnoSJ5xVmIL4qgz+s4qf2TnJIMyZFUFMGH+9vE7mXynAlHSZ/NdTmmow86muD0myUkVQ=="}}}Copy the code

So what exactly does package-lock.json do?

Because the packages we downloaded on NPM follow the big version. Minor version. Version definition of minor version. For example, in the example above, bootstrap version 4.3.1 was installed using the NPM install command, and package.json typically specifies the scope of the package when installing the plug-in package, meaning that only the larger version of the plug-in package is qualified. If you use a feature in 4.3.1 that was removed in 4.4.4, your code will definitely be buggy.

The package-lock.json file exists in the project, because the package version and source information referenced in the project are locked in this file, when someone else copies the code and is ready to restore, it can be loaded into the exact version of the component you used in development. Of course, if you modify the referenced package information, the package-lock.json file will be updated synchronously when the NPM install command is executed.

The version restrictions for packages are shown below.

Specified version: In this example, the bootstrap version is 4.3.1. Only the specified 4.3.1 version will be installed during reinstallation.

Tilde + specified version: for example, ~1.2.2 means that the latest version of 1.2.x is installed (not less than 1.2.2), but 1.3.x is not installed, that is, the major and minor versions are not changed during installation.

We repeat that we install the latest version of 1.x.x (at least 1.2.2), but we do not install 2.x.x, that is, we do not change the larger version number when we install. Note that if the large version number is 0, the insertion behavior is the same as the tilde.

Latest: Indicates the latest version of the installation package.

Gulp configuration

Once we have added the component packages we need to use through NPM, we need to consider how we will use them in our project.

ASP.NET Core projects typically use StaticFileMiddleware to fetch static files from Web projects. The “{contentroot}/wwwroot” directory is the default root directory for static files in the external project, that is, we need to move the NPM package to the wwwroot file.

Manual replication? Em, that seems like a lot of work.

However, now that we’re using Node.js, we can use gulp.js as a task automator to do this for us, but you can use other tools as you like.

By using gulp.js, you can automatically move files, package compressed JS, CSS, image, delete files, etc., saving you from having to bundle compressed CSS and JS files.

We need to install gulp as a devDependencies dependencies for gulp, and we need to download a lot of stuff. The installation process depends on your network.

The gulp plugin used in this project is shown below. If you need to copy the command line below, delete the comments when executing.

//gulp.js NPM install gulp --save-dev // compressed CSS NPM install gulp-clean-css --save-dev // merged file NPM install gulp-concat --save-dev // zip js NPM install gulp-uglify --save-dev // rename NPM install gulp-rename --save-dev // delete files and folders Rimraf --save-dev // NPM install gulp-changed --save-devCopy the code

The package.json file is as follows.

{
  "version": "1.0.0"."name": "aspnetcore.npm.tutorial"."private": true."devDependencies": {
    "gulp": "^ 4.0.1." "."gulp-changed": "^ 3.2.0"."gulp-clean-css": "^ 4.2.0"."gulp-concat": "^ 2.6.1." "."gulp-rename": "^ 1.4.0." "."gulp-uglify": "^ 3.0.2." "."rimraf": "^ 2.6.3." "
  },
  "dependencies": {
    "bootstrap": "^ 4.3.1." "."jquery": "^ 3.4.1 track"."popper.js": "^ 1.14.7"}}Copy the code

After installing all the gulp component packages, create a gulpfile.js file in the root path of our project with the contents shown below.

/// <binding BeforeBuild='min' Clean='clean' ProjectOpened='auto' />
"use strict";

// Load the used gulp plugin
const gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-clean-css"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    changed = require("gulp-changed");


// define the path of each file under wwwroot
const paths = {
    root: "./wwwroot/".css: './wwwroot/css/'.js: './wwwroot/js/'.lib: './wwwroot/lib/'
};

//css
paths.cssDist = paths.css + "**/*.css";// Match the path of all CSS files
paths.minCssDist = paths.css + "**/*.min.css";// Matches the path of all compressed CSS files
paths.concatCssDist = paths.css + "app.min.css";// Zip all CSS into a single CSS file

//js
paths.jsDist = paths.js + "**/*.js";// Match all js file paths
paths.minJsDist = paths.js + "**/*.min.js";// Matches the compressed js file path
paths.concatJsDist = paths.js + "app.min.js";// Compress all js files into a js file path


// Use NPM to download the front-end component package
const libs = [
    { name: "jquery".dist: "./node_modules/jquery/dist/**/*.*" },
    { name: "popper".dist: "./node_modules/popper.js/dist/**/*.*" },
    { name: "bootstrap".dist: "./node_modules/bootstrap/dist/**/*.*"},];// Clear compressed files
gulp.task("clean:css", done => rimraf(paths.minCssDist, done));
gulp.task("clean:js", done => rimraf(paths.minJsDist, done));

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

// Move the NPM downloaded front-end component package to the wwwroot path
gulp.task("move", done => {
    libs.forEach(function (item) {
        gulp.src(item.dist)
            .pipe(gulp.dest(paths.lib + item.name + "/dist"));
    });
    done()
});

// Compress each CSS file to the corresponding min.css
gulp.task("min:css", () = > {return gulp.src([paths.cssDist, "!" + paths.minCssDist], { base: "." })
        .pipe(rename({ suffix: '.min' }))
        .pipe(changed('. '))
        .pipe(cssmin())
        .pipe(gulp.dest('. '));
});

// Consolidate all CSS files into app.min.css
gulp.task("concatmin:css", () = > {return gulp.src([paths.cssDist, "!" + paths.minCssDist], { base: "." })
        .pipe(concat(paths.concatCssDist))
        .pipe(changed('. '))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

// Each js file is compressed to the corresponding min.js
gulp.task("min:js", () = > {return gulp.src([paths.jsDist, "!" + paths.minJsDist], { base: "." })
        .pipe(rename({ suffix: '.min' }))
        .pipe(changed('. '))
        .pipe(uglify())
        .pipe(gulp.dest('. '));
});

// Compress all js files into app.min.js
gulp.task("concatmin:js", () = > {return gulp.src([paths.jsDist, "!" + paths.minJsDist], { base: "." })
        .pipe(concat(paths.concatJsDist))
        .pipe(changed('. '))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

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


// Automatic execution after listening for file changes
gulp.task("auto", () => {
    gulp.watch(paths.css, gulp.series(["min:css"."concatmin:css"]));
    gulp.watch(paths.js, gulp.series(["min:js"."concatmin:js"]));
});
Copy the code

There are four main apis in gulp.js, just as gulpfile in our project is more about using third-party plugins, we just need to pipe each step of the task to the task queue. For full API documentation, you can go to the official website to see in detail => Gulp.

Gulp.src: loads files based on a match or path;

Gulp. dest: outputs the file to the specified path.

Gulp.task: Defines a task;

Gulp. watch: Listens for file changes

When we created the task, deleted the referenced third-party component package under the wwwroot path, ran our sample project, and no doubt the entire page style was lost.

/// <binding BeforeBuild='min' Clean='clean' ProjectOpened='auto' />
Copy the code

By combining binding events with the GULp API, we can achieve our requirements. In this case, I have a task that automatically listens for file changes when the project is opened. In this case, whenever I change the CSS or JS file, gulp will automatically compress the file for me.

PS: If you tie a task to an event when the project is opened, it will be automatically executed the next time the project is opened.

conclusion

This chapter introduces how to use NPM to manage our front-end component package in our ASP.NET Core project. At the same time, we use gulp to perform some tasks of moving and compressing files. With the development of front-end, front-end development is more and more standardized, but also more and more toward the back end, we as a traditional sense of the back end program ape, when it comes to front-end development, if we can use these can standardize the characteristics of our front-end projects, or very good. Because their level is also very vegetables, many things are not very detailed, may also need you to further explore in practical use, after all, practice is the real knowledge.

Of the pit

Personal Profile: Born in 1996, born in a fourth-tier city in Anhui province, graduated from Top 10 million universities. .NET programmer, gunslinger, cat. It will begin in December 2016. NET programmer career, Microsoft. NET technology stalwart, aspired to be the cloud cat kid programming for Google the best. NET programmer. Personal blog: yuiter.com blog garden blog: www.cnblogs.com/danvic712