[Vue] Some front-end knowledge you need to know before learning Vue

Source article: KuangStudy

01. Overview and front-end tool vscode installation

  1. Download and install VSCode

    Download address: VSCode

02、Nodejs

2.1. Install NodeJs

Installation address: NodeJs

Verify successful installation
Insert image description here

Introduction

  • Node is a development platform that allows JavaScript to run on the server side. It makes JavaScript a scripting language on par with server-side languages ​​such as PHP, Python, Perl, and Ruby. Released in May 2009 and developed by Ryan Dahl, it essentially encapsulates the Chrome V8 engine.
  • Simply put, Node.js is JavaScript running on the server. Node.js is a platform built on the Chrome JavaScript runtime. The underlying architecture is: javascript. File suffix: .js
  • Node.js is an event-driven I/O server-side JavaScript environment based on Google's V8 engine. The V8 engine executes Javascript very quickly and has very good performance.

image-20220530222456559

Chinese API documentation: http://nodejs.cn/api/

Getting started tutorial: http://nodejs.cn/learn

2.2. Getting started with NodeJs

2.2.1. Quick Start-hello world

  1. Create folder NodeJs

  2. Create a new file helloword.js

    //相当于java的 System.out.print("hello word!")
    console.log("hello word!");
    
  3. Open a command line terminal: Ctrl + Shift + y

    Run: node .\helloword.js

    Result: hello word!

    image-20220531221558957

The kernel of the browser consists of two core parts:

  • DOM rendering engine
  • javascript parser (js engine)
  • js runs inside the js engine in the browser kernel

summary

Node.js is a JavaScript program that runs independently of the browser environment and is based on the v8 engine.

2.2.2. Node-implement request response

  1. Create new helloserver.js

    //导入模块是require 就类似java 的 import
    const http = require('http');
    //1. 创建一个httpserver服务
    http.createServer(
        function(require, response) {
          
          
            //浏览器怎么认识  hello server!
            //这句话的含义就是:告诉浏览器将以text/plain的形式去解析
            response.writeHead(200,{
          
          'Content-Type':'text/html'});
            //response.writeHead(200,{'Content-Type':'text/plain'});
            //给浏览器输出内容
            response.end("<strong>hello server!</strong>")
    
        }
    ).listen(8888);
    //2. 监听端口8888
    //3. 启动运行服务
    //4. 在浏览器访问http://localhost:8888
    console.log("你启动的服务是http://localhost:8888")
    

2.2.3. Node-operate mysql database

Reference: https://www.npmjs.com/package/mysql

  1. Install mysql dependencies

  2. Create a new database nodejsdb and table kss_user

    /*
     Navicat MySQL Data Transfer
     Source Server         : localhost
     Source Server Type    : MySQL
     Source Server Version : 60011
     Source Host           : localhost:3306
     Source Schema         : testdb
     Target Server Type    : MySQL
     Target Server Version : 60011
     File Encoding         : 65001
     Date: 20/01/2021 21:38:55
    */
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    -- ----------------------------
    -- Table structure for kss_user
    -- ----------------------------
    DROP TABLE IF EXISTS `kss_user`;
    CREATE TABLE `kss_user`  (
      `id` int(11) NOT NULL,
      `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
    -- ----------------------------
    -- Records of kss_user
    -- ----------------------------
    INSERT INTO `kss_user` VALUES (1, '学相伴');
    INSERT INTO `kss_user` VALUES (2, '广东');
    SET FOREIGN_KEY_CHECKS = 1;
    
  3. Define db.js to operate

    //导入mysql依赖包,mysql属于第三方的模块,就类似于java.sql
    var mysql = require("mysql");
    
    //1. 创建一个mysql连接对象
    //2. 配置数据连接的信息
    var connection = mysql.createConnection({
          
          
        host:"127.0.0.1",
        port:3306,
        user:"root",
        password:"123456",
        database:"nodejsdb"
    });
    //3. 开辟连接
    connection.connect();
    //4. 执行CRUD
    connection.query("select * from kss_user", function(error, results, fields) {
          
          
        //如果查询异常,直接抛出
        if(error)throw error;
        //查询成功,控制台打印
        console.log("results=", results);
    });
    //5. 关闭连接
    connection.end();
    
    

03、ES6

3.1. ES6 Overview

ECMAScript is a scripting programming language standardized by Ecma International (formerly the European Computer Manufacturers Association) through ECMA-262. This language is widely used on the World Wide Web. It is often called JavaScript or JScript, so it can be understood as a standard for JavaScript, but in fact the latter two are implementations and extensions of the ECMA-262 standard.

Quick reading development of ECMAScript:

image-20220601224616514

The programming language JavaScript is an implementation and extension of ECMAScript. ECMAScript is a syntax specification standardized by ECMA (a standards organization similar to W3C). ECMAScript defines:

[Language Grammar] – Grammar parsing rules, keywords, statements, declarations, operators, etc.

[Type] – Boolean, number, string, object, etc.

[Prototype and inheritance]

Built-in objects and functions

[Standard Library] – [JSON], [Math], [Array Method], [Object Introspection Method], etc.

The ECMAScript standard does not define related functions of HTML or CSS, nor does it define [Web API] like DOM (Document Object Model), which are all defined in independent standards. ECMAScript covers JS usage scenarios in various environments, whether it is a browser environment or a non-browser environment like [node.js].

The historical versions of the ECMAScript standard are 1, 2, 3, and 5.

So why isn't there a 4th edition? In fact, in the past, there was indeed a plan to release version 4 that proposed a huge number of new features, but in the end it was scrapped because the idea was too radical (this version of the standard once had an extremely complex built-in static that supported generics and type inference. type system).

ES4 was controversial, and when the standards committee finally stopped developing ES4, its members agreed to release a relatively modest version of ES5 and then went on to work on some more substantial new features. This explicit negotiation protocol was eventually named "Harmony", therefore, the ES5 specification contains these two sentences

ECMAScript is a dynamic language that is constantly evolving.

Important technical improvements will continue to be made in future versions of the specification

The improved version ES5 released in 2009 introduced [Object.create()], [Object.defineProperty()], [getters] and [setters], [strict mode] and [JSON] objects.

ES6: It is the next generation standard of JavaScript language, officially released in June 2015. Its goal is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language.

summary:

ECMAScript is the syntax specification for front-end js; it can be applied in various js environments. Such as: browser or node.js environment.

It has many versions: es1/2/3/5/6, with many new features, which can be used in the js environment.

3.2. ES6 syntax: let and const commands

Definition of let and const

New html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //传统定义变量和常量的方式
        var name = "Genius Sue";
        var link = "https://blog.csdn.net/Daears";
        var PI = Math.PI;
        console.log(name);
        console.log(link);
        console.log(PI);

        //ES6定义的方式
        let name1 = "Genius Sue";
        let link1 = "https://blog.csdn.net/Daears";

        //定义常量
        const PI1 = Math.PI;
        console.log(name1);
        console.log(link1);
        console.log(PI1);
    </script>
</body>
</html>

The difference between let, const and var

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //let 和 const解决
        //1.var的变量穿透问题
        //2.常量修改的问题
        for(var i=0;i<5;i++) {
      
      
            console.log(i);
        }
        //这里造成变量穿透
        console.log(i);

        var PI = Math.PI;
        //这里的常量可以被修改
        PI = 100;
        console.log(PI);
    </script>
    
</body>
</html>

Optimized

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        for(let i=0;i<5;i++) {
      
      
            console.log(i);
        }
        //这里会报错: i is not defined
        // console.log(i);

        const PI = Math.PI;
        //这里会报错: Assignment to constant variable.
        PI = 100;
        console.log(PI);
    </script>
    
</body>
</html>

In actual development and production, if it is a small program, uniapp or some scaffolding, you can boldly use let and const

But if you are developing web, it is recommended that you still use var. Because some lower version browsers still do not support let and const

summary:

  • let : mutable variable
  • const: is a constant
  • var: the most original

3.3. ES6 syntax: template string

Before: We always used '' or "" to wrap strings

Now: `` [backtick]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //字符串会牵涉到动态部分
         var person = {
      
      
            "name": "Genius Sue",
            "address": "福州"
        }
        let str = "传统==>我是" + person.name + ",我在" + person.address + "上班";
        console.log(str);
        

        //ES6的语法模板字符串
        let str2 = `ES6==>我是${ 
        person.name},我在${ 
        person.address}上班`;
        console.log(str2);
    </script>
</body>
</html>

3.4. ES6 syntax: function default parameters and arrow functions

Function default parameters

Just add a default value after the method parameters

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /*函数默认参数
        如果某个形参有了默认参数,则位于这个形参之后的所有形参都要有默认参数。
        有了默认参数,仍然可以传递实参,这样形参的值按照传递的实参优先。
        */
        function sum(a=100, b=100) {
      
      
            return a + b;
        }

        //若函数参数没有默认值,为undefine,所以结果为NaN -> Not a Number
        var result = sum(100);
        console.log(result);
    </script>
</body>
</html>

arrow function

Arrow functions simplify the definition of functions and allow us to avoid using the function keyword

You can refer to the blog: (1 message) Anonymous function (Lambda expression) and arrow function_maomaolaoshi's blog-CSDN blog_arrow function and lambda expression

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //箭头函数 -- 重点 类似于java lambda表达式  
        //(在未来的项目开发中,比如小程序,uniapp 一些常见的脚手架大量使用)
        //--------------情况1-----------
        var sum = function(a, b) {
      
      
            return a + b;
        }

        //改进1
        var sum = (a, b) => {
      
      
            return a + b;
        }

        //改进2
        var sum = (a, b) => a + b


        /*通过上面可以找到规律
        1.去掉function
        2.在括号后面加箭头
        3.如果逻辑代码只有一行可以不用{},如果是return 可以连return一起省略
        4.如果函数参数只有一个,括号也可以省去,若有多个或者没有参数则不能省去
        */

        var array = [1, 2, 3, 4, 5];
        // var newarray = array.map(function(item) {
      
      
        //     return item*2;
        // });
        //改进
       var newarray = array.map(item=>item*2);
       console.log(newarray);

        //--------------情况2-----------
        var sum2 = function (a, b, c) {
      
      
            let num = a + b + c;
            return num;
        }
        //改进
        var sum2 = (a, b, c) => {
      
      
            let num = a + b + c;
            return num;
        }

        //--------------情况3-----------
        var sum3 = function (a) {
      
      
            return a * 2;
        }
        //改进
        var sum3 = a => a * 2;

    </script>
</body>

</html>

3.5. ES6 syntax: object initialization abbreviation

It means: if the key and value in an object have the same name, they can be defined as one.

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let info = {
      
      
            titile: "ES6",
            link: "https://blog.csdn.net/Daears",
            do: function () {
      
      
                console.info("带薪学习");
            }
        }
        //es6对象简写
        //因为对象是key:value存在
        //1. 如果key和变量名字一致,可以只定义一次即可
        //2. 如果value是一个函数,可以把function去掉
        let titile = "大前端";
        let link = "https://blog.csdn.net/Daears";
        var info2 = {
      
      
            // titile:titile,
            titile,
            // link:link,
            link,
            do() {
      
      
                console.info("带薪学习");
            }
        }
        console.log(info2);
        console.log(info2.titile);
        info2.do();


        var info3 = {
      
      
            titile,
            link,
            sum(a=0,b=0) {
      
      
                return a + b;
            }
        }
        info3.titile="标题";
        info3.link="链接地址";
        
        console.log(info3);
        console.log(info3.sum(100,200));

    </script>

</body>

</html>

Case:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>对象简写</title>
</head>

<body>

    <from action="#">
        <p>
            用户名:<input type="text" id="username">
        </p>
        <p>
            密码:<input type="text" id="password">
        </p>
        <p>
            <input type="button" value="登录" onclick="login()">
        </p>

    </from>
    <script>
        function login() {
      
      
            var username = $("#username").val();
            var password = $("#password").val();
            // 发送ajax
            $.ajax({
      
      
                type: "post",
                // 对象简写
                data: {
      
       username, password },
                // 原始写分
                //data:{username:username,password:password},
                success() {
      
      
                }
            });
        }
    </script>
</body>

</html>

3.6. ES6 syntax: object destructuring

core code

Object destructuring - es6 provides some quick ways to obtain object properties and behaviors

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        //对象是key:value 存在,获取对象属性和方法的方式有两种
        //1. 通过.
        //2. 通过[]
        var info2 = {
      
      
            titile: "大前端",
            link: "https://www.baidu.com",
            go() {
      
      
                console.info("做地铁上班");
            }
        }


        // console.log(info2);
        // 通过.的方式
        console.log(info2.titile);
        info2.go();

        // 通过[]的方式
        console.log(info2["titile"]);
        info2["go"]();

        //es6对象结构--其实就是快读获取属性和方法的方式  前提:默认情况titile必须是jsonkey.
        var {
      
       titile, go } = info2;
        //还原代码
        // var titile = info2.titile;
        // var go = info2.go
        console.log(titile);
        // console.log(link);  //报错:link is not defined
        go();


        var {
      
       titile2, go } = info2;
        console.log(titile2);//undefined


        //可以用冒号取小名
        var {
      
       titile: title } = info2;
        console.log(title);


    </script>

</body>

</html>

3.7. ES6 syntax: propagation operator

Propagate properties of one object to another object

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 1: 定义一个对象
        var person = {
      
      
            name: '卢本伟',
            age: 3,
            address:"上海",
            say:function(){
      
      
                console.log("请阿姨喝一杯卡布奇诺");
            }
        };

        // 2: 对象解构
        var {
      
       name, age,...person2 } = person;
        console.log("======对象解构======");
        console.log(name);
        console.log(age);
        console.log(person2);

        // =========================== ... 对象融合=====================
        var person2 = {
      
      
            ...person,
            gender: 1,
            tel: 11012012580
        };
        console.log("======对象融合======");
        console.log(person2);
        // =========================== ... 对象取值=====================
        // ... 对象取值
        var person3 = {
      
      
            name: "厂长",
            gender: 1,
            tel: "4396",
        };
        console.log("创建一个对象", person3);
         // ...person4 把剩下没取走给person4。
        var {
      
       name, gender, ...person4 } = person3;
        console.log("======把剩下没取走给我======");
        console.log(name);
        console.log(age);
        console.log(person4);
        // =================场景分析 -----伪代码========================
        // 模拟后台:异步查询返回用户数据 如下:
        function findUsers() {
      
      
            $.get("xxxxx", function (res) {
      
      
                var res = {
      
      
                    pages: 11,
                    pageSize: 10,
                    pageNo: 1,
                    firstFlag: true,
                    lastFlag: false,
                    total: 123,
                    data: [{
      
      }, {
      
      }, {
      
      }, {
      
      }],
                };
                // ==========================对象 ... 取值===============
                var {
      
       data: users, ...pagesjon } = res;
                //等价于
                /*  var users = res.data;
                   var pagesjon = {
                    res = {
                        pages:11,
                        pageSize:10,
                        pageNo:1,
                        firstFlag:true,
                        lastFlag:false,
                        total:123,
                    }; */
            })
        }
    </script>

</body>

</html>

3.8. ES6 syntax: use of array map and reduce methods

Application scenarios of the map method in arrays

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //对arr数组中每个元素*2
        let arr = [1, 2, 3, 4, 5, 6, 7];
        console.log("原数组", arr);
        //传统方式
        let newarr = [];
        for (let i = 0; i < arr.length; i++) {
      
      
            newarr.push(arr[i] * 2);
        }
        console.log("操作后数据(传统)", newarr);
        /*
        map方式 -- 自带循环功能,
        可以将原数组中的所有元素通过一个函数进行处理,
        并放入到一个新数组中并返回该新数组。
        */
        // let newarr2 = arr.map(function (item) {
      
      
        //     return item * 2;
        // });
        // 简写
        let newarr2 = arr.map(item => item * 2);
        console.log("操作后数据(map)", newarr2);

        //=========================
        var users = [{
      
       name: "Genius Sue", age: 18 }, {
      
       name: "GCD", age: 18 }];

        //如果不使用return会改变原来的数组
        users.map(ele => {
      
      
            ele.age = ele.age + 1;
            ele.address = "福州";
        });
        console.log("操作后数据", users);

    </script>
</body>

</html>

reduce

reduce(function(), initial value (optional)):

Receives a function (required) and an initial value (optional). The function receives two parameters:

  • The first parameter is the result of the last reduce process
  • The second parameter is the next element to be processed in the array.
    reduce() will reduce the elements in the array from left to right, and use the processing result as the first parameter of the next reduce. If it is the first time, the first two elements will be used as calculation parameters, or the user-specified initial value will be used as the starting parameter.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        //a = 1,b = 2   sum = 3;
        //a = 3,b = 3   sum = 6;
        // let sum = arr.reduce(function (a, b) {
      
      
        //     return a + b;
        // });
        //简写
        let sum = arr.reduce((a, b) => a + b);
        console.log(sum);//55
    </script>

</body>

</html>

04. NPM package manager

4.1. Introduction

Official website: https://www.npmjs.com/

NPM is a full node package manager. It is a node.js package management tool. It is the world's largest module ecosystem. All modules in it are open source and free. It is also a node.js package management tool, similar to the role of maven.

#在命令提示符输入 npm -v 可查看当前npm版本
npm -v

Insert image description here

4.2. Use npm to manage projects

  1. Create folder npm

  2. Project initialization

    #建立一个空文件夹,在命令提示符进入该文件夹  执行命令初始化
    npm init
    #按照提示输入相关信息,如果是用默认值则直接回车即可。
    #name: 项目名称
    #version: 项目版本号
    #description: 项目描述
    #keywords: {Array}关键词,便于用户搜索到我们的项目
    #最后会生成package.json文件,这个是包的配置文件,相当于maven的pom.xml
    #我们之后也可以根据需要进行修改
    
    #如果想直接生成 package.json 文件,那么可以使用命令
    npm init -y
    

4.3. Modify npm image

  1. Modify npm image

    The official packages managed by NPM are all downloaded from https://www.npmjs.com/, but this website is very slow in China.

    It is recommended to use Taobao NPM mirror https://npmmirror.com/

    The Taobao NPM image is a complete npmjs.com image, and the synchronization frequency is currently once every 10 minutes to ensure that it is as synchronized with the official service as possible.

    npm install -g cnpm --registry=https://registry.npmmirror.com

  2. Set mirror address

    #经过下面的配置,以后所有的 npm install 都会经过淘宝的镜像地址下载
    npm config set registry https://registry.npm.taobao.org 
    #查看npm配置信息
    npm config list
    

4.4、npm install

#使用 npm install 安装依赖包的最新版,
#模块安装的位置:项目目录\node_modules
#安装会自动在项目目录下添加 package-lock.json文件,这个文件帮助锁定安装包的版本
#同时package.json 文件中,依赖包会被添加到dependencies节点下,类似maven中的 <dependencies>
npm install jquery
#如果安装时想指定特定的版本
npm install [email protected]
#devDependencies节点:开发时的依赖包,项目打包到生产环境的时候不包含的依赖
#使用 -D参数将依赖添加到devDependencies节点
npm install --save-dev eslint
#或
npm install -D eslint
#全局安装
#Node.js全局安装的npm包和工具的位置:用户目录\AppData\Roaming\npm\node_modules
#一些命令行工具常使用全局安装的方式
npm install -g webpack
#npm管理的项目在备份和传输的时候一般不携带node_modules文件夹
npm install #根据package.json中的配置下载依赖,初始化项目

4.5. Other commands

#更新包(更新到最新版本)
npm update 包名
#全局更新
npm update -g 包名
#卸载包
npm uninstall 包名
#全局卸载
npm uninstall -g 包名

05、Babel

5.1. Introduction to Babel

babel is a widely used transcoder that can convert es6 code into es5 code so that it can be executed in the existing environment.

5.2. Installation of Babel

Install the command line transcoding tool

Babel provides the babel-cli tool for command line transcoding. Its installation command is as follows:

npm install -g babel-cli
#查看是否安装成功
babel --version

Insert image description here

5.3. Use of Babel

  1. Create folder babel

  2. Initialize project

    npm init -y
    
  3. Create the file src/example.js. Here is a piece of ES6 code:

    //ES6
    let name = "Genius Sue";
    const title = "福州";
    let arr = [1,2,3,4,5,6,7,8,9,10];
    let newarr = arr.map(a=>a*2);
    console.log(newarr);
    
  4. config.babelrc

    Babel's configuration file is .babelrc, which is stored in the root directory of the project. This file is used to set transcoding rules and plug-ins. The basic format is as follows:

    {
          
          
        "presets": [],
        "plugins": []
    }
    

    Set the transcoding rules in the presets field and add the es2015 rules to .babelrc

    {
          
          
        "presets": ["es2015"],
        "plugins": []
    }
    
  5. Install the transcoder and install it in the project

    npm install --save-dev babel-preset-es2015
    
    #或者 
    
    cnpm install --save-dev babel-preset-es2015
    
  6. Transcode

    babel src -d dist
    

    Automatic generated

Insert image description here

Comparison before and after conversion

Insert image description here

expand:

# npm install --save-dev csv-loader xml-loader
# 转码结果写入一个文件
mkdir dist1
# --out-file 或 -o 参数指定输出文件
babel src/example.js --out-file dist1/compiled.js
# 或者
babel src/example.js -o dist1/compiled.js
# 整个目录转码
mkdir dist2
# --out-dir 或 -d 参数指定输出目录
babel src --out-dir dist2
# 或者
babel src -d dist2

The final project directory structure

Insert image description here

5.4. Custom script

  1. Rewrite package.json

    {
          
          
      "name": "babel",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
          
          
        "test": "echo \"Error: no test specified\" && exit 1",
    	"dev":"babel src -d dist"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
          
          
        "babel-preset-es2015": "^6.24.1"
      }
    }
    
    

    Mainly added"dev": "babel src -d dist2"

  2. When transcoding, execute the following command

    npm run dev
    

    babel src -d distIt also has the same effect as typing directly in the command above.

06. Modularization

6.1. Introduction

The background of modularization

As websites gradually become "Internet applications", the Javascript code embedded in web pages becomes larger and more complex.

Javascript modular programming has become an urgent need. Ideally, developers only need to implement the core business logic, and other modules can be loaded by others. However, Javascript is not a modular programming language. It does not support concepts such as "class" (class), package (package), or "module" (module).

Modular specification

  • CommonJS modular specification
  • ES6 Modularity Specification

6.2. CommonJS specifications

Each file is a module and has its own scope. Variables, functions, and classes defined in a file are private and not visible to other files.

  1. Create a folder MODULEPRO and a new directory module

  2. Create new commonjs/four arithmetic operations.js

    // 定义成员:
    const sum = function(a,b){
          
          
        return a + b
    }
    const subtract = function(a,b){
          
          
        return a - b
    }
    const multiply = function(a,b){
          
          
        return a * b
    }
    const divide = function(a,b){
          
          
        return a / b
    }
    // 导出成员:
    module.exports = {
          
          
        sum: sum,
        subtract: subtract,
        multiply: multiply,
        divide: divide
    }
    
  3. Create new commonjs/import module.js

    //require 引入模块,注意:当前路径必须写 ./
    
    const m = require("./四则运算.js");
    
    console.log(m.sum(1,2));
    //Common JS 模块化开发 exports 和 require来导入、导出模块。 必须先导出了才能使用
    

6.3. ES6 modular specification

ES6 uses export and import to export and import modules.

  1. Create a new es6 directory under module

  2. Create a new src/userApi.js export module

    export function getUserList() {
          
          
        console.log("获取用户列表");
    };
    
    export function save() {
          
          
        console.log("保存数据");
    };
    
  3. Create a new src/userTest.js import module

    //只取需要的方法即可,多个方法用逗号分隔
    import {
          
           getUserList, save } from "./userApi.js";
    
    getUserList();
    save();
    
    //注意:这时的程序无法运行的,因为ES6的模块化无法在Node.js中执行,需要用Babel编辑成ES5后再执行。
    
  4. At this time, if you run node .\src\userTest.js directly, an error will be reported.

  5. You need to use babel for downgrade, first initialize the project

    npm init -y
    
  6. Create a new .babelrc configuration file

    {
        "presets": ["es2015"],
        "plugins": []
    }
    
  7. Install transcoder

    npm install --save-dev babel-preset-es2015
    
  8. Modify package.json to add build

    {
      "name": "es6",
      "version": "1.0.0",
      "description": "",
      "main": "userApi.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "babel src -d dist"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "babel-preset-es2015": "^6.24.1"
      }
    }
    
    
  9. Execute command transcoding

    npm run build
    
  10. Run program

    node .\dist\userTest.js
    

Insert image description here

6.4. ES6 modular writing method 2

  1. Create a new es62 directory under module

  2. Create a new src/userApi.js export module

    export default {
          
          
        getUserList() {
          
          
            console.log("获取用户列表");
        },
        save() {
          
          
            console.log("保存数据");
        }
    }
    
  3. Create a new src/userTest.js import module

    import user from "./userApi.js";
    
    user.getUserList();
    
    user.save();
    
  4. Execute command transcoding

    npm run build
    

    5. Run the program

    node dist/userComponent2.js
    

07、webpack

7.1. What is webpack

webpack is a front-end resource loading/packaging tool. It will perform static analysis based on module dependencies, and then generate corresponding static resources for these modules according to specified rules.

From the figure, we can see that Webpack can convert a variety of static resources js, css, and less into a static file, reducing page requests.

image-20220615223509088

Chinese official documentation: https://www.webpackjs.com/

7.2. Webpack installation

  1. Global installation

    npm install -g webpack webpack-cli
    
  2. Check if the installation is successful

    webpack -v
    

Insert image description here

7.3. Initialize project

  1. Create webpack folder

    npm init -y
    
  2. Create src folder

  3. Create common.js under src

    exports.info = function (str) {
          
          
        document.write(str);
    }
    
  4. Create utils.js under src

    exports.add = function (a, b) {
          
          
        return a + b;
    }
    
  5. Create main.js under src

    const common = require('./common');
    const utils = require('./utils');
    
    common.info('Hello World!'+utils.add(100,100));
    

7.4. js packaging

  1. Create the configuration file webpack.config.js in the webpack directory

    //导入path模块,nodejs内置模块
    const path = require("path");
    
    //定义js打包的规则
    module.exports = {
          
          
        //1.入口函数从哪里开始进行编译打包
        entry: "./src/main.js",
        //2:编译成功以后把内容输出到哪里去
        output: {
          
          
            //2-1:定义输出的指定目录,__dirname当前项目的根目录,生成一个dist文件夹
            path: path.resolve(__dirname, "./dist"),
            //2-2:合并的js文件存在dist/bundle.js文件中
            filename: "bundle.js"
        }
    }
    
  2. Execute compilation command from command line

    webpack --mode=development
    #执行后查看bundle.js 里面包含了上面两个js文件的内容并进行了代码压缩
    

    You can also configure the project's npm running command and modify the package.json file

    //...
    "scripts": {
        //...
        "build": "webpack --mode=development"
     }
     //...,
    

    Run npm command to perform packaging

    npm run build
    
  3. Create index.html in the webpack directory and reference bundle.js

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script src="dist/bundle.js"></script>
    </body>
    </html>
    
  4. View index.html in the browser

Insert image description here

7.5. css packaging

  1. Install style-loader and css-loader

    webpack本身只能处理JavaScript模块,如果要处理其他类型的文件,就需要使用loader进行转换
    
    loader可以理解是模块和资源的转换器
    
    首先我们需要安装loader插件
     css-loader是将css装载到JavaScript
     style-loader是让JavaScript认识css
    
    npm install --save-dev style-loader css-loader
    
  2. Modify webpack.config.js

    //导入path模块,是nodejs的内置模块
    const path = require("path");
    
    //定义js打包的规则
    module.exports = {
          
          
        //1.入口函数从哪里开始进行编译打包
        entry: "./src/main.js",
        //2:编译成功以后把内容输出到哪里去
        output: {
          
          
            //2-1:定义输出的指定目录,__dirname当前项目的根目录,生成一个dist文件夹
            path: path.resolve(__dirname, "./dist"),
            //2-2:合并的js文件存在dist/bundle.js文件中
            filename: "bundle.js"
        },
        module:{
          
          
            rules:[
                {
          
          
                    test: /\.css$/,    //打包规则应用到以css结尾的文件上
                    use: ['style-loader', 'css-loader']
                }
            ]
        }
    }
    
  3. Create style.css in the src folder

    body{
          
          
        background:pink;
        font-size: 40px;
    }
    
  4. Modify main.js and introduce style.css in the remote navigation

    const common = require('./common');
    const utils = require('./utils');
    
    const css = require('./style.css');
    
    common.info('Hello World!'+utils.add(100,100));
    
  5. Run packaging command

    npm run dev
    
  6. View index.html in the browser to see the effect

Insert image description here

08、vue-element-admin

vue-element-admin is a backend front-end solution, which is implemented based on vue] and element-ui. It uses the latest front-end technology stack, built-in i18 internationalization solution, dynamic routing, permission verification, refines typical business models, and provides rich functional components. It can help you quickly build enterprise-level middle and back-end product prototypes. I believe that no matter what your needs are, this project can help you.

Official website address: https://panjiachen.github.io/vue-element-admin-site/zh/

Source code: https://github.com/PanJiaChen/vue-element-admin

# 克隆项目
git clone https://github.com/PanJiaChen/vue-element-admin.git

# 进入项目目录
cd vue-element-admin

# 安装依赖
npm install

# 建议不要直接使用 cnpm 安装依赖,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题
npm install --registry=https://registry.npm.taobao.org

# 启动服务
npm run dev

Browser access http://localhost:9527

image-20220621224922778

Here are some problem-solving blogs I found when I ran into a problem:

When npm installed vue-element-admin, I encountered the git.EXE ls-remote -h -t ssh://[email protected] error error code: 128

How to install node-sass correctly

fatal: unable to access ‘https://github.com/nhn/raphael.git/‘: OpenSSL SSL_read: Connection was rese

Guess you like

Origin blog.csdn.net/Daears/article/details/126970635