node.js introduction notes


A lot about node has been introduced earlier JS theoretical knowledge, but lack of practical combat. Actual combat is still more important. Therefore, I hope to record these basic knowledge and key points of actual combat of the project like thinkPHP before, which can be easily read by myself and shared with you. If there is anything wrong, you are welcome to criticize and correct in the comment area.

1. Introduction of webpack

I believe you should be familiar with webpack, a project packaging tool. I only know its advantages and basic usage here. If you want to study it more deeply, you can check it( webpack official website ), or you can check the notes I read vue2 before:( Vue learning notes (IV) -- basic use of webpack )Here is a brief summary of the basic usage of webpack:
(1) First, install the third-party dependent webpack and webpack cli (just install in the production environment);
(2) Next, install copy webpack plugin and html webpack plugin. The former is used to copy special files to the specified location during packaging, and the latter is used to process html entry files during packaging.
(3) Then we need to install webpack dev server, which is a webpack dependency used for hot overloading in the production environment. When the code is updated, the service will be restarted automatically to improve our development efficiency.
(4) Create a webpack in the root directory config. The default configuration file is webp.
The following shows the file structure and webpack config. JS file configuration information:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
	//Specifies whether the mode currently used is production mode or development mode
    mode: "development",
    //Package entry file
    entry: {
        app: "./src/index.js",
    },
    //Package export file
    output: {
        path: path.join(__dirname, "./dist"), //Only absolute paths can be used
        filename: "index.js",
    },
    //Configure plug-ins
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "./src/index.html"),
            filename: "index.html",
            inject: true,//Whether to inject the entry file into this html
        }),
        //It is mainly to deal with ico files, because ico is a special file,
        //Cannot be automatically packaged into dist directory by webpack
        new CopyWebpackPlugin({
            patterns: [{
                from: "./src/favicon.ico",
                to: path.join(__dirname, "./dist"),
            }, ],
        }),
    ],
    //Configure server
    devServer: {
        compress: true,
        port: 9000,
    },
};

It should be noted that the path used in the plug-in, especially the path with output meaning, needs to use absolute path, so the path module is introduced. Why not directly use the html file as the entry file? There's no need to migrate it. This is mainly because the start project in front-end redesign is usually an app JS project startup file, especially in vue ecology. In addition, in order to facilitate us to quickly start or package the project, we can configure npm script information (the working principle of the script has been mentioned before, which will not be repeated):

  "build": "npx webpack",
  "start": "npx webpack-dev-server"

2.webpack introduces art template

In order to better understand and use node JS, let's build a node The background environment of JS can be regarded as a kind of actual combat, during which the art template template will be used. In addition, let's talk about how to use webpack to import art template templates. Refer to the official website:( art-template):
(1) To download the art template template engine, you need to install two dependencies: Art template and art template loader. The latter is convenient to use webpack to package the project;
(2) To facilitate fast refresh, we configure webpack dev server and clean webpack plugin third-party dependencies. The former automatically restarts the service, while the latter automatically deletes and recreates the dist file every time it restarts;
(3) Next, adjust the project structure and webpack config. JS file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
    mode: "development",
    devtool: "source-map",
    //Used to quickly and accurately locate bug s,
    //The default packaging will make the location of the bug deviate from the actual location
    
    //Package entry file
    entry: {
        app: "./src/app.js",
    },
    //Package export file
    output: {
        path: path.join(__dirname, "./dist"), //Only absolute paths can be used
        filename: "app.js",
    },
    //Import art template loader
    module: {
        rules: [
            // template file
            {
                test: /\.art$/,
                loader: "art-template-loader",
            },
        ],
    },
    //Configure plug-ins
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "./public/index.html"),
            filename: "index.html",
            inject: true,
        }),
        new CopyWebpackPlugin({
            patterns: [{
                from: "./public/favicon.ico",
                to: path.join(__dirname, "./dist"),
            }, ],
        }),
    ],
    //Configure server
    devServer: {
        // contentBase: path.join(__dirname, "./dist"),
        compress: true,
        port: 9000,
    },
};

A pit is encountered during configuration. If the views directory is placed in the src directory, node will be caused_ There is an error in the use of modules, because the views file of art template is placed in the root directory by default. You haven't found out how to customize it. Just put it in the root directory.

3. Project route initialization

In order to save the development energy of the front desk, use( AdminLTE backend template )At the same time, in order to facilitate the management of routing, use( sme-router ), this route relies on a framework similar to express. Because there are many codes involved, let's briefly talk about the development ideas and key codes:
(1) Firstly, the project still uses the classic RMVC mode design;
(2) In addition, let's review the functions of various current dependencies:

"devDependencies": {
        "art-template-loader": "^1.4.3",//Template engine packaging loader
        "clean-webpack-plugin": "^4.0.0",//Used to quickly refresh the dist directory
        "copy-webpack-plugin": "^10.2.4",//Used to copy files to the specified location
        "html-webpack-plugin": "^5.5.0",//Used to process html pages and perform injection
        "webpack": "^5.68.0",//Used to package items
        "webpack-cli": "^4.9.2",//Packaging tool's own dependency
        "webpack-dev-server": "^4.7.4"//Used to automatically restart the service
    },
    "dependencies": {
        "art-template": "^4.13.2",//template engine
        "jquery": "^3.6.0",//juery
        "sme-router": "^0.12.8"//Routing tool
    }
    //other
    source-map//Easy to quickly check bug s
    AdminLTE//Reduce the workload of front-end template based bootstrap

(3) Briefly show the structure of the project:

Note: store the html code block stripped of html and body tags in the views file, and put it in the index Set the "socket" corresponding to the code block in html < div id = "root" > < / div >:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test home page</title>

    <!-- Google Font: Source Sans Pro -->
    <!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> -->
    <!-- Font Awesome -->
    <link rel="stylesheet" href="./libs/css/all.min.css">
    <link rel="stylesheet" href="./libs/css/ionicons.min.css">
    <link rel="stylesheet" href="./libs/css/icheck-bootstrap.min.css">
    <link rel="stylesheet" href="./libs/css/adminlte.min.css">
    <link rel="stylesheet" href="./libs/webfonts/font.css">
    <link rel="stylesheet" href="./libs/css/jqvmap.min.css">
    <link rel="stylesheet" href="./libs/css/OverlayScrollbars.min.css">
    <link rel="stylesheet" href="./libs/css/tempusdominus-bootstrap-4.min.css">
    <link rel="stylesheet" href="./libs/css/summernote-bs4.min.css">
    <link rel="stylesheet" href="./libs/css/daterangepicker.css">
    <link rel="stylesheet" href="./libs/webfonts/fa-regular-400.woff2">
    <link rel="stylesheet" href="./libs/webfonts/fa-solid-900.woff2">
    <style>
        .login-page {
            align-items: center;
            background-color: #e9ecef;
            display: -ms-flexbox;
            display: flex;
            -ms-flex-direction: column;
            flex-direction: column;
            height: 100vh;
            -ms-flex-pack: center;
            justify-content: center;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini">
    <div id="root"></div>
    <!-- jQuery -->
    <script src="./libs/js/jquery.min.js"></script>
    <!-- Bootstrap 4 -->
    <script src="./libs/js/bootstrap.bundle.min.js"></script>
    <!-- AdminLTE App -->
    <script src="./libs/js/adminlte.min.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="./libs/js/demo.js"></script>
</body>

</html>

libs stores various static resource dependencies and shows the webpack configuration file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
    mode: "development",
    devtool: "source-map",
    //Package entry file
    entry: {
        "js/app": path.join(__dirname, "./src/app.js"),
    },
    //Package export file
    output: {
        path: path.join(__dirname, "./dist"), //Only absolute paths can be used
        filename: "[name].js",
    },
    module: {
        rules: [
            // template file
            {
                test: /\.art$/,
                loader: "art-template-loader",
            },
        ],
    },
    //Configure plug-ins
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "./public/index.html"),
            filename: "index.html",
            inject: true,
        }),
        new CopyWebpackPlugin({
            patterns: [{
                    from: "./public/favicon.ico",
                    to: path.join(__dirname, "./dist"),
                },
                {
                    from: "./public/libs/",
                    to: path.join(__dirname, "./dist/libs/"),
                },
            ],
        }),
    ],
    //Configure server
    devServer: {
        compress: true,
        port: 9000,
    },
};

Basic use of Routing:

//src/router/index.js
import SMERouter from "sme-router";
import index from "../controllers/index";
import login from "../controllers/login";
//Put in the code block socket
const router = new SMERouter("root");

router.route("/", index);
router.route("/login", login);
export default router;
//src/controllers/index.js
import indexTpl from "../../views/index.art";
const indexHtml = indexTpl({});
const index = (req, res, next) => {
    res.render(indexHtml);
};
export default index;

It should be noted that after configuring the route, the route will not match automatically, so you need to use router go("/"); Jump to the specified route. Secondly, for module export, you need to use r eport default.
In this way, the initial construction of the whole project is completed, and then the back-end routing and data transmission. For the front-end, too many front-end pages have been written. In fact, the back-end is familiar with the simple CRUD when thinking PHP. Other notes on the back-end will be updated later, because it is necessary to take the postgraduate entrance examination, and there may be less time to read these. If you see here, thank you very much, because your reading is the driving force for me to update. In fact, I didn't expect it myself, node JS will have so many notes to read. Finally, I have to thank the video tutorial provided by Gu Yi San at station B.

Keywords: node.js Vue.js Webpack

Added by Wesf90 on Mon, 14 Feb 2022 16:08:37 +0200