Build front-end development environment

1.2 understand front and rear end separation development

The separation of front end and back end has become the industry standard way of use for Internet project development,
Effectively decouple through nginx+tomcat (or add a nodejs in the middle),
And the separation of front and back ends will be the future large-scale distributed architecture, elastic computing architecture, micro service architecture
Multi terminal services (multiple clients, such as browser, vehicle terminal, Android, IOS, etc.) lay a solid foundation.

The old way was:

1. Product Manager / Leader / customer needs

2. Make design drawing of UI

3. Front end engineer makes html page

4. The back-end engineer sets the html page into a jsp page (the front and back ends are strongly dependent, and the back-end must wait for the front-end html to set the jsp. If the html changes, it will be more painful and the development efficiency will be low)

5. Integration problems

6. Front end rework

7. Back end rework

8. Secondary integration

9. Successful integration

10. Delivery

The new approach is:

1. Product Manager / Leader / customer needs

2. Make design drawing of UI

3. Interface & Data & parameters agreed at the front and rear end

4. Front and back-end parallel development (without strong dependence, front and back-end parallel development can be used. If the requirements change, as long as the interface & parameters remain unchanged, there is no need to modify the code on both sides, and the development efficiency is high)

5. Front and rear end integration

6. Front page adjustment

7. Successful integration

8. Delivery

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-sv1hnd1j-1600908671128)( https://blog.csdn.net/qq_37574218/article/details/image/1-1-1.png )]

1.3 front end technical architecture

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-u6quz9df-1600908671130)( https://blog.csdn.net/qq_37574218/article/details/image/1-1-2.png )]

Architecture Description: node Vue.js as the core JS front end technology ecological architecture

2 Node.js

2.1 what is a node js

Simply put, node JS is the JavaScript running on the server.

Node.js is a platform based on Chrome JavaScript runtime.

Node.js is an event driven I/O server JavaScript environment. It is based on Google's V8 engine. The V8 engine executes JavaScript very fast and has very good performance.

2.2 Node.js installation

1. Download the node corresponding to your system JS version:

https://nodejs.org/en/download/

(the version we use now is 8.9.4, which is also provided in the resources)
2. Select the installation directory to install

Default

3. Test

Enter the command at the command prompt

node -v
1

The current node version is displayed

2.3 quick start

2.3.1 console output

Now let's do the simplest small example to demonstrate how to output on the console and create a text file Demo1 JS, code content

var a=1;
var b=2;
console.log(a+b);
123

We enter commands at the command prompt

node demo1.js
1

2.3.2 using functions

Create a text file demo2 js

var c=add(100,200);
console.log(c);
function add(a,b){
	return a+b;
}
12345

Enter a command at the command prompt

node demo2.js
1

After running, you can see that the output result is 300

2.3.3 modular programming

Create text file demo3_1.js

exports.add=function(a,b){
	return a+b;
}
123

Create text file demo3_2.js

var demo= require('./demo3_1');
console.log(demo.add(400,600));
12

We enter commands at the command prompt

node demo3_2.js
1

The result is 1000

2.3.4 creating a web server

Create a text file demo4 js

var http = require('http');
http.createServer(function (request, response) {
    // Send HTTP header 
    // HTTP status value: 200: OK
    // Content type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
    // Send response data "Hello World"
    response.end('Hello World\n');
}).listen(8888);
// The terminal prints the following information
console.log('Server running at http://127.0.0.1:8888/');
1234567891011

http is the built-in web module of node

We enter commands at the command prompt

node demo4.js
1

After the service starts, we open the browser and enter the web address

http://localhost:8888/

You can see the output of the web page Hello World

Are you very excited? Ctrl+c terminates the run.

2.3.5 understanding server rendering

We created demo5 JS, write the above example in the form of a loop

var http = require('http');
http.createServer(function (request, response) {
    // Send HTTP header 
    // HTTP status value: 200: OK
    // Content type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
    // Send response data "Hello World"
	for(var i=0;i<10;i++){
		response.write('Hello World\n');
	}  
	response.end('');	
}).listen(8888);
// The terminal prints the following information
console.log('Server running at http://127.0.0.1:8888/');
1234567891011121314

We start the service by entering a command at the command prompt

node demo5.js
1

Browser address bar entry http://127.0.0.1:8888 You can see the query results.

We right-click "view source code" and find that there is no for loop statement we wrote, but 10 Hello worlds directly, which shows that this loop is completed on the server rather than the browser (client). This is very similar to our original JSP.

2.3.6 receiving parameters

Create demo6 js

var http = require('http');
var url = require('url');
http.createServer(function(request, response){
    response.writeHead(200, {'Content-Type': 'text/plain'});
    // Parsing url parameters
    var params = url.parse(request.url, true).query;
    response.write("name:" + params.name);
    response.write("\n");
    response.end();
}).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');
1234567891011

We enter commands at the command prompt

node demo6.js
1

Test results in browser

3-pack resource manager NPM

3.1 what is NPM

The full name of NPM is Node Package Manager, which is a node package management and distribution tool. In fact, we can understand NPM as Maven at the front end

Through npm, we can easily download js library and manage front-end projects

The latest version of node JS has integrated npm tools. Enter npm -v at the command prompt to view the current npm version

3.2 NPM command

3.2.1 initialization works

The init command is the project initialization command.

Create an empty folder and enter the folder at the command prompt to execute command initialization

npm init
1

Enter relevant information according to the prompt. If the default value is used, press enter directly.

Name: project name

Version: project version number

Description: item description

keywords: {Array} keyword, which is convenient for users to search our project

Finally, a package. XML file will be generated JSON file, which is the package configuration file, is equivalent to maven's POM xml

We can also modify it as needed later.

3.2.2 local installation

The install command is used to install a module. If we want to install the express module (the web framework of node), the output command is as follows:

npm install express
1

The yellow warning message appears and can be ignored. Please rest assured that you have successfully executed the command.

A node already appears in this directory_ Modules folder and package lock json

node_ The modules folder is used to store the downloaded js Library (equivalent to maven's local warehouse)

package-lock.json is when node_modules or package A file that is automatically generated when JSON changes. The main function of this file is to determine the dependencies of the currently installed package, so that the same dependencies can be generated during subsequent reinstallation, while ignoring the updates of some dependencies in the process of project development.

Let's open the package JSON file and found that the downloaded express has been added to the dependency list

Definition of version number:

Specified version: for example, 1.2.2,Follow the "big version".minor version .The format of "minor version" stipulates that only the specified version is installed during installation.

Wave sign( tilde)+Specified version: for example~1.2.2,Indicates installation 1.2.x Latest version of (not less than 1).2.2),But do not install 1.3.x,That is, the major version number and minor version number will not be changed during installation.

Insert number( caret)+Specified version: for exampleˆ1.2.2,Indicates installation 1.x.x Latest version of (not less than 1).2.2),But do not install 2.x.x,In other words, the large version number will not be changed during installation. It should be noted that if the major version number is 0, the behavior of the insertion number is the same as that of the wave number. This is because it is in the development stage at this time. Even if the minor version number changes, the program may be incompatible.

latest: Install the latest version.
1234567

3.2.3 global installation

Just now we used local installation, which will install the js Library in the current directory, while using global installation will install the library in your global directory.

If you don't know where your global directory is, execute the command

npm root -g
1

My global directory is

C:\Users\Administrator\AppData\Roaming\npm\node_modules

For example, to install jquery globally, enter the following command

npm install jquery -g
1

3.2.4 batch download

We downloaded some codes from the Internet and found that only package JSON, no node_modules folder. At this time, we need to download these js libraries again through the command

Enter the directory (the directory where package.json is located) and enter the command

npm install
1

At this point, npm will automatically download package The js library that JSON depends on

3.2.5 Taobao NPM image

Sometimes we use npm to download resources very slowly, so we can install a CNMP (Taobao image) to speed up the download speed.

Enter the command to install Taobao image globally.

npm install -g cnpm --registry=https://registry.npm.taobao.org
1

After installation, we can use the following command to view the version of cnpm

cnpm -v
1

Using cnpm

cnpm install Need to download js library
1

3.2.6 operation engineering

If we want to run a project, use the run command

If package The script defined in JSON is as follows

dev is the development phase test run

Build is a build and compile project

lint is running js code detection

Now let's try running dev

npm run dev
1

3.2.7 compilation Engineering

Next, we test the compilation of a code After compiling, we can deploy the project to nginx~

The compiled code will be placed in the dist folder. First, delete the files in the dist folder and enter the command prompt

npm run build
1

After generation, we will find that there are only one static page and one static folder

This project is called single page web application (SPA), which is an application with only one Web page. It is a Web application that loads a single HTML page and dynamically updates the page when the user interacts with the application.

In fact, we call webpack to realize packaging. We will introduce webpack in the following chapters

4 Webpack

4.1 what is Webpack

Webpack is a front-end resource loading / packaging tool. It will conduct static analysis according to the dependency of modules, and then generate corresponding static resources according to the specified rules.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ykyxgmof-1600908671132)( https://blog.csdn.net/qq_37574218/article/details/image/1-1.jpg )]

As can be seen from the figure, Webpack can convert various static resources js, css and less into a static file, reducing page requests. Next, let's briefly introduce the installation and use of Webpack

4.2 Webpack installation

Global installation

npm install webpack -g
npm install webpack-cli -g
12

View version number after installation

webpack -v
1

4.3 quick start

4.3.1 JS packaging

(1) Create src folder, create bar js

exports.info=function(str){
   document.write(str);
}
123

(2) Create logic under src js

exports.add=function(a,b){
	return a+b;
}
123

(3) Create main under src js

var bar= require('./bar');
var logic= require('./logic');
bar.info( 'Hello world!'+ logic.add(100,200));
123

(4) Create configuration file webpack config. JS, which is in the same level directory as src

var path = require("path");
module.exports = {
	entry: './src/main.js',
	output: {
		path: path.resolve(__dirname, './dist'),
		filename: 'bundle.js'
	}
};
12345678

The meaning of the above code is: read the main in the src folder in the current directory JS (entry file) content, package the corresponding JS file, put the packaged file into the dist folder of the current directory, and the packaged JS file is named bundle js

(5) Execute compile command

webpack
1

Check the bundle after execution js will find that it contains the contents of the above two js files

(7) Create index HTML, reference bundle js

<!doctype html>
<html>
  <head>  
  </head>
  <body>   
    <script src="dist/bundle.js"></script>
  </body>
</html>
12345678

Test call index HTML, you will find content output

4.3.2 CSS packaging

(1) Install style loader and CSS loader

Webpack itself can only handle JavaScript modules. If you want to handle other types of files, you need to use loader for conversion.

Loader can be understood as a converter of modules and resources. It is a function that accepts the source file as a parameter and returns the conversion result. In this way, we can load any type of module or file through require, such as CoffeeScript, JSX, LESS or pictures. First, we need to install the relevant loader plug-ins. css loader loads css into javascript; Style loader is to let javascript know css

cnpm install style-loader css-loader --save-dev
1

(2) Modify webpack config. js

var path = require("path");
module.exports = {
	entry: './src/main.js',
	output: {
		path: path.resolve(__dirname, './dist'),
		filename: 'bundle.js'
	},
	module: {
		rules: [  
            {  
                test: /\.css$/,  
                use: ['style-loader', 'css-loader']
            }  
        ]  
	}
};
12345678910111213141516

(3) Create a css folder in the src folder, and create css1 under the css folder

body{
 background:red;
}
123

(4) Modify main JS, introducing CSS1 css

require('./css1.css');
1

(5) Rerun webpack

(6) Run index HTML see if the background turns red?

5 development tool VsCode

5.1 introduction to vscode

VSCode (Visual Studio Code) is a lightweight code editor produced by Microsoft,
Importantly, it can run on the desktop of Windows, OS X and Linux operating systems.
Visual Studio Code has built-in support of JavaScript, TypeScript and node JS language support,
It also provides rich extension libraries and runtime for other languages such as C++, C#, Python, PHP, etc.

5.2 VsCode installation and configuration

5.2.1 installation

Download from official website https://code.visualstudio.com/

It can be installed by default

5.2.2 plug in installation

VsCode can make the editor more powerful by installing plug-ins

The following are common plug-ins for front-end development engineers

(1)HTML Snippets

Super practical and elementary H5 code snippets and tips

(2)HTML CSS Support

Let the html tag write a class intelligent prompt. The new version of the style supported by the current project already supports scss file retrieval

(3)Debugger for Chrome

Let vscode map the debug function of chrome. Vscode can be used to interrupt the debugging of static pages. It's really 666~

(4)vetur

Plug in syntax highlighting, intelligent perception, Emmet, etc. required by vue framework

(5)VueHelper

Snippet code snippet

5.2.3 automatic saving of configuration

Click menu: file – check auto save

6 ES6

6.1 what is ES6

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

Language grammar – syntax parsing rules, keywords, statements, declarations, operators, etc.

type – Boolean, number, string, object, etc.

Prototype and inheritance

Of built-in objects and functions Standard libraryJSON,Math,Array method,Object introspection method Wait.

ECMAScript standard does not define functions related to HTML or CSS, nor does it define functions similar to DOM (document object model) Web API , these are defined in separate standards. ECMAScript covers the usage scenarios of JS in various environments, whether browser environment or similar node.js Non browser environment.

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

So why not version 4? In fact, in the past, it was planned to release version 4, which proposed a large number of new features, but it was finally abolished because the idea was too radical (this version of the standard once had an extremely complex built-in static type system supporting generics and type inference).

ES4 was controversial. When the standards committee finally stopped developing ES4, its members agreed to release a relatively modest version of ES5, and then continue to develop some more substantive new features. This explicit negotiation agreement is finally named "Harmony". Therefore, the ES5 specification contains such two sentences

ECMAScript is a dynamic language that is constantly evolving.

Important technical improvements will continue in future versions of the specification

The improved version ES5 released in 2009 introduces Object.create(),Object.defineProperty(),getters and setters,Strict mode as well as JSON Object.

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of JavaScript language, which was officially released in June 2015. Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language.

6.2 Node. Using ES6 in JS

ES6 + is great, but many advanced functions node does not support, so you need to use babel to convert it to ES5

(1) babel conversion configuration, add to the project root directory babelrc file

{
  "presets" : ['es2015']
}
123

(2) Installation of conversion module es6

cnpm install babel-preset-es2015 --save-dev
1

(3) Global install command line tools

cnpm install  babel-cli -g
1

(4) Use

babel-node js file name
1

6.3 new features of grammar

6.3.1 variable declaration

We all know that before ES6, var keyword declared variables. Wherever it is declared, it is considered to be declared at the top of the function (not within the function, that is, at the top of the global scope). This is the function variable promotion, for example

  function aa() {
    if(bool) {
        var test = 'hello man'
    } else {
        console.log(test)
    }
  }
1234567

The above code is actually:

function aa() {
    var test // Variable promotion
    if(bool) {
        test = 'hello man'
    } else {
        //The test value accessed here is undefined
        console.log(test)
    }
    //The test value accessed here is undefined
  }
12345678910

So don't worry about whether bool is true or false. In fact, test will be declared anyway.

Next, the protagonist of ES6 will appear:

We usually use let and const to declare. Let represents variable and const represents constant. Let and const are both block level scopes. How to understand this block level scope? Inside a function, inside a code block. Look at the following code

 function aa() {
    if(bool) {
       let test = 'hello man'
    } else {
        //test cannot be accessed here
        console.log(test)
    }
  }
12345678

6.3.2 constant declaration

const is used to declare constants. See the following code

const name = 'lux'
name = 'joe' //If the value is assigned again, an error will be reported
12

6.3.3 template string

es6 template characters are a blessing for developers. They solve the pain points of ES5 in string function.

The first purpose is basic string formatting. Embed expressions into strings for splicing. Defined by ${}.

    //es5 
    var name = 'lux'
    console.log('hello' + name)
    //es6
    const name = 'lux'
    console.log(`hello ${name}`) //hello lux
123456

Second, in ES5, we use backslash () to do multi line string or string line by line splicing. ES6 reverse quotation mark (` `) is directly handled.

    // es5
    var msg = "Hi \
    man!"
    // es6
    const template = `<div>
        <span>hello world</span>
    </div>`
1234567

6.3.4 function default parameters

ES6 provides default values for parameters. This parameter is initialized when the function is defined so that it can be used when the parameter is not passed in.

Look at the example code

    function action(num = 200) {
        console.log(num)
    }
    action() //200
    action(300) //300
12345

6.3.5 arrow function

The interesting part of ES6 is the quick writing of functions. That is, the arrow function.

The three most intuitive features of arrow function.

1 no function keyword is required to create a function

2 omit the return keyword

3 inherit the this keyword of the current context

Look at the following code (ES6)

 (response,message) => {
    .......
 }
123

Equivalent to ES5 code

function(response,message){
    ......
}
123

6.3.6 object initialization abbreviation

ES5 we write objects in the form of key value pairs, which may have duplicate names. for example

function people(name, age) {
        return {
            name: name,
            age: age
        };
    }
123456

The above code can be abbreviated as

  function people(name, age) {
        return {
            name,
            age
        };
    }
123456

6.3.7 deconstruction

Arrays and objects are the most commonly used and important representations in JS. In order to simplify the extraction of information, ES6 adds deconstruction, which is the process of decomposing a data structure into smaller parts

ES5 we extract the information in the object in the following form

    const people = {
        name: 'lux',
        age: 20
    }
    const name = people.name
    const age = people.age
    console.log(name + ' --- ' + age)
1234567

Do you feel familiar? Yes, that's how we got object information before ES6, one by one. Now, the deconstruction of ES6 allows us to take data from objects or arrays and save it as variables, such as

//object
    const people = {
        name: 'lux',
        age: 20
    }
    const { name, age } = people
    console.log(`${name} --- ${age}`)
    //array
    const color = ['red', 'blue']
    const [first, second] = color
    console.log(first) //'red'
    console.log(second) //'blue'
123456789101112

6.3.8 Spread Operator

Another interesting feature in ES6 is the Spread Operator, which also has three points... Next, let's show its purpose. Assemble objects or arrays

    //array
    const color = ['red', 'yellow']
    const colorful = [...color, 'green', 'pink']
    console.log(colorful) //[red, yellow, green, pink]
    
    //object
    const alp = { fist: 'a', second: 'b'}
    const alphabets = { ...alp, third: 'c' }
    console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"
123456789

6.3.9 import and export

Import import module, export export module

lib.js

let fn0=function(){
    console.log('fn0...');
}
export {fn0}
1234

demo9.js

import {fn0} from './lib'
fn0();
12

Note: node(v8.x) itself does not support the import keyword, so we need to use babel's command-line tool to execute it (see Section 6.2 for configuration)

babel-node demo9
    //array
    const color = ['red', 'blue']
    const [first, second] = color
    console.log(first) //'red'
    console.log(second) //'blue'
123456789101112

6.3.8 Spread Operator

Another interesting feature in ES6 is the Spread Operator, which also has three points... Next, let's show its purpose. Assemble objects or arrays

    //array
    const color = ['red', 'yellow']
    const colorful = [...color, 'green', 'pink']
    console.log(colorful) //[red, yellow, green, pink]
    
    //object
    const alp = { fist: 'a', second: 'b'}
    const alphabets = { ...alp, third: 'c' }
    console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"
123456789

6.3.9 import and export

Import import module, export export module

lib.js

let fn0=function(){
    console.log('fn0...');
}
export {fn0}
1234

demo9.js

import {fn0} from './lib'
fn0();
12

Note: node(v8.x) itself does not support the import keyword, so we need to use babel's command-line tool to execute it (see Section 6.2 for configuration)

babel-node demo9

Posted by kylebragger on Sun, 15 May 2022 20:39:46 +0300