es6 modularization, detailed use of websoket (with simple chat room source code) and webpack

1, es6 modularization

1.1 steps of using es6 Modularization:

(1) Expose data using export

(2) Importing modules using import

(3) Introduce the js file into html, and pay attention to setting type="module" for the attribute of script

1.2 export

1.2.1 exposure

Single exposure syntax 1:

export let variable 1 = value 1;  
export var variable 2 = value 2; 
export function(){}
...

Batch exposure syntax 2:

let variable 1 = value 1;
let variable 2 = value 2;
function method name () {}
...
‚Äč
export {variable 1, variable 2, method name,,}

Description: expose multiple data. Note that the name of the variable is consistent with the name of the exposure

1.2.2 introduction

Syntax:

import {variable}   from file  
import {variable as   New variable name} from file

Description: load module

1.3 export default

1.3.1 exposure

Default exposure syntax:

export default content

Description: only one data is exposed

Note: the default exposure in the same file can be used once

1.3.2 introduction

Syntax:

import variable from "file path"

2, websocket

2.1 introduction to websocket [ key ]

Websocket is a new protocol added to HTML5. Using websocket protocol can enable the client to communicate with the server in both directions, that is, in addition to the client sending messages to the server, the server can also actively push messages to the client.

Before websocket, ajax + timer can be used to realize this similar function of chat room.

2.2 socket.io module

Use steps:

(1) Download socket.io

npm install socket.io@2

(2) Use express to set up the server and configure socket.io

(3) Configure client

(4) Access the server to establish a connection

(5) Business code

2.3 common methods

2.3.1 webSocket

Syntax:

let webSocket = require('socket.io')
webSocket(server)

Description: returns the socket.io object. The server parameter is the server object returned by app.listen

2.3.2 io

Syntax:

IO (websocket server address)

Description: the client establishes a connection with the server

2.3.3 on: receive message

Syntax 1:

io.on( 'connect',callback )

Description 1: syntax 1: when the user connects to the server, the connect event is triggered. Note: the front end needs IO (websocket server address)

Syntax 2:

websocketObj.on( event,callback )

Description 2: syntax 2 means that the client can listen to the message sent by the server, or the server can listen to the message sent by the client

2.3.4 emit: send message

Syntax 1:

Websocketobj.emit (event, message object)

Description 1: trigger an event and send a message

Syntax 2:

Io.sockets.emit (event, message object)

Description 2: trigger all client listening events and send messages

2.3.5 join: join the room

Syntax:

Websocketobj.join (room id, event callback)

Description: Join room

2.3.6 to: send the message to the designated room

Syntax:

Io. To (room number). Emit (event, message object)

Description: triggers the user event of the object's room number and sends a message

2.4 group chat

Server code:

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
//Listening event: is there a new websocket connection
io.on('connection', (socket) => {
    //Receive messages sent by the client:
    socket.on('chat', d => {
        //console.log(d, 999);
        //The server pushes the received message to all clients: io.emit()
        io.emit('rechat', d);
    });
});
server.listen(3000);
//Process user login to chat room
app.get('/login', (req, res) => {
    let { usr = '' } = req.query;
    if (usr == '') {
        res.send(`<script>alert('User name cannot be empty');location.href='login.html';</script>`);
        return;
    }
    res.cookie('UNAME', usr); //Save user name to cookie
    res.send(`<script>location.href='2-chat.html';</script>`);
});


//Open static resources
app.use(express.static(path.join(__dirname, 'www')))

The client code is as follows:

<!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>
    <script src="socket.io/socket.io.js"></script>
    <style>
        div {
            position: fixed;
            left: 20px;
            bottom: 20px;
            background-color: blanchedalmond;
            padding: 10px;
        }
    </style>
</head>

<body>
    <ul>
        <!-- <li>XXX Say:???</li>
        <li>XXX Say:???</li> -->
    </ul>
    <div>
        <input type="text" id="msg">&nbsp;
        <input type="button" value="send out" id="btn">
    </div>
    <script>
        let socket = io(); //Create websocket connection
        let btnObj = document.getElementById('btn');
        let msbObj = document.getElementById('msg');
        let ulObj = document.getElementsByTagName('ul')[0];
        btnObj.onclick = function() {

            let curUser = ''; //Currently logged in user name
            let cookieValue = document.cookie; //Get cookie
            if (cookieValue.indexOf('UNAME') == -1) { // Not logged in
                alert('Please log in first');
                location.href = 'login.html';
            } else { //Logged in
                let arr = cookieValue.split(';');
                for (let val of arr) {
                    if (val.indexOf('UNAME') != -1) {
                        let arr2 = val.split('=');
                        curUser = arr2[1];
                    }
                }
            }
            let msgVal = msbObj.value; //Get the chat content entered by the user
            if (msgVal != '') {
                socket.emit('chat', `${curUser}Say: ${msgVal}`); //Send message to server
            }
        }
        //The client receives messages pushed by the server:
        socket.on('rechat', data => {
            //console.log(data, 1111);
            ulObj.innerHTML = `<li>${data}</li>` + ulObj.innerHTML;
        });
    </script>
</body>

</html>

2.5 zone (room) communication

The code of the server is as follows:

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
    // console.log( socket.handshake.query );
    let roomid = socket.handshake.query.roomid //Receiving room number
    //2. Users on the current connection join a room
    socket.join(roomid, () => {
        // console.log('join room succeeded: '+ room ID)
        socket.emit('event1', 'Join successfully')
    })
    socket.on('front_message1', (message) => {
        // console.log(message, 8888);
        io.to(roomid).emit('server_message1', message) //Point to point
    })
})
server.listen(3000);
//Managed static resources
app.use(express.static(path.join(__dirname, 'www')));

The client code is as follows:

<!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>
    <input type="text" id="roomid" placeholder="Enter room number">
    <button id="rooms">Join the room</button>
    <input type="text" id="msg" placeholder="Enter message content">
    <button id="btn">send message</button>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        let socket = null
            //1. Click the add room button, and then establish a connection with the socket server
        $('#rooms').click(function() {
            if ($('#roomid').val() == '') {
                alert('Please enter the room number')
                return
            }
            //Create a connection and tell the server to join a room
            socket = io('http://localhost:3000?roomid=' + $('#roomid').val());
            // Client listening events
            socket.on('server_message1', (message1) => {
                console.log(message1)
            })
            //This event is triggered after the server joins the room to tell the client
            socket.on('event1', (message) => {
                alert(message)
            })
        })
        $('#btn').click(function() {
            if (!socket) {
                alert('Please join a room')
                return
            }
            //Trigger server-side events and send messages
            socket.emit('front_message1', $('#msg').val())
        })
    </script>
</body>

</html>

3, webpack

3.1 webpack concept

Webpack front-end resource modular management and packaging tool. Many loose modules can be packaged into front-end resources required by the online environment. At the same time, webpack depends on the node environment. Webpack has very strict version requirements for some modules

Note: webpack is a tool that front-end developers need.

Development environment:

Production environment:

3.1.1 why learn webpack

3.2 preparation

webpack official website Webpack Chinese document | webpack Chinese website

(1) Install node

(2) Install webpack and webpack cli, NPM I webpack@4 webpack- cli@3 -g

(3) Check whether the webpack is successfully installed. webpack --version

3.3 introduction to the core of webpack

Key nameconceptexplain
contextEntrance starting pointThe basic directory, an absolute path, is used to resolve the entry point from the configuration
entryEntrance (required)The name of the configuration package entry file
outputExit (required)Where to output after packaging, and the output file name
moduleLoader configurationIn the corresponding array of rules, define object rules
pluginsPlug in configurationConfigure plug-in functions (plug-ins have some functions that webpack does not have, such as compressing html files)

3.3.1 webpack.config.js syntax format

module.exports = {
    context: entry starting point,
    entry: entrance,
    output:{
        path: export directory,
        filename: file name,
    },
    module: { 
        rules: [ 
            Loader rules 
        ]
    },
    plugins:[
        plug-in unit
    ]
}

3.4 webpack usage

3.4.1 getting to know webpack for packaging js

3.4.2 css processing

Understanding of loader

Steps:

CSS loader 3 version style loader 2 version

npm i css-loader@3 style-loader@2 -D

devDependencies:

dependencies:

module: {
	rules: [ 
		{ 
			test: /\.css$/, 
			use: [ 'style-loader', 'css-loader' ]
		}
	]
}

3.4.3 separation of css

extract-text-webpack-plugin@next plug-in unit

Install Download

npm i extract-text-webpack-plugin@next -D

Loader modify configuration

const ExtractTextPlugin = require("extract-text-webpack-plugin"); 
Rules: [/ / usage rules of loader
	{
		test: /\.css$/,
		use: ExtractTextPlugin.extract({/ / create an extract loader from an existing loader.
			fallback: "style-loader", 
        	Use: "CSS loader" / / loader is used to convert resources into a separate CSS file
        })
	}
]

Plug in configuration

new ExtractTextPlugin("style.css"), / / output file name

Error reporting Description:

Error: Cannot find module 'webpack/lib/Chunk'

Solution: Download in the project directory webpack@4

3.4.4 package less

  1. You need to install less and less loader to parse less code and load less files

    npm i less@3 less-loader@7 -D
  2. Configure the loader in webpack.config.js and parse the. less file

    { 
    	test: /\.less$/, 
    	use: ['style-loader', 'css-loader', "less-loader"]
    }
  3. However, it is found that the css code is not separated, so you need to use the extract text webpack plugin configuration to separate the css code

    { 
    	test: /\.less$/, 
    	use: ExtractTextPlugin.extract({ 
    		fallback: "style-loader", 
    		use: ['css-loader', "less-loader"]
    	})
    }
  4. Observe the style code in the less file in style.css after packaging

3.4.5 generate html

HTML webpack plugin.

download

npm i html-webpack-plugin@4 -D

Note: what the plug-in needs to display is imported into webpack.config.js

plugins property

plugins:[
        new HtmlWebpackPlugin({/ / plugin configuration object)
            filename: "index.html", / / output file name (view in dist directory)
            Template: _dirname + "/ index. HTML", / / use this file as the benchmark (note the absolute path, because this file is not under src)
            favicon: "./assets/favicon.ico", / / insert the packaged favicon icon
            minify: {/ / compress the html file,
                    Collapsepooleanattributes: true, / / whether to abbreviate attributes in boolean format, such as: disabled="disabled" abbreviated as disabled
                    minifyCSS: true, / / whether to compress css in html (compression using clean css). The default value is false
                    minifyJS: true, / / whether to compress js in html (compression using uglify js)
                    removeAttributeQuotes: true, / / whether to remove the quotation marks of the attribute. The default is false
                    removeComments: true, / / whether to remove comments. The default is false
                    removeCommentsFromCDATA: true, / / comments deleted from scripts and styles. The default is false
             }
        }) / / the array element is a new object of the plug-in
    ]

Description of errors

Cannot find module "webpack/lib/node/NodeTeplatePlugins"

In the project of installing HTML webpack plugin, separately install the version corresponding to the global webpack locally

npm i webpack@4 -D

3.4.6 static resource processing

  1. Two loader modules need to be downloaded

    • url-loader,file-loader

Download:

npm i url-loader@4 file-loader@6 -D

Note: webpack thinks that pictures are also a module, so it needs a loader to parse pictures)

2.webpack.config.js loader configuration:

Add this configuration to the module.

 {
     Test: / \ (png|jpg|jpeg|gif|svg) $/, / / process these ending files
     use: 'url-loader'
 }

//If you need to introduce this when dealing with font icons
{
  test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
  loader: 'url-loader'
}

3.4.7 jquery usage

In a webpack packaged project, use the jQuery function

  1. Download the jquery module,

    npm i jquery

  2. Introduce jquery into main.js,

    import $ from 'jquery'

3.4.8 hot renewal

  1. The webpack dev server will monitor the changes of files in real time and automatically package them into memory instead of generating the dist directory on the hard disk

  2. Webpack dev server, which also starts a local server to support you to access the packaged html web pages

    • Download webpack dev server - G

    • npm i webpack-dev-server -g

    • webpack-dev-server --version

  3. Run the command under the project: webpack dev server can start the hot update server. It will run in memory according to webpack.config.js in the directory.

  4. Note: if the configuration (webpack.config.js) file is modified, the terminal still needs to be restarted. If it is the code under src, it will be packaged automatically

  5. Note: by default, the file name to be packaged for output must be index.html file

  6. By default, our hot update server is started on port number: 8080, and all projects are opened and accessed on this server

  7. When the development is completed, you also need to use the webpack command to package to the dist directory.

webpack.config.js configuration:

devServer: {/ / you can configure webpack dev server here
         port: 9090, / / modify the port number. The default value is 8080
         open: true, / / automatically call the default browser to open
}

Tags: ECMAScript Webpack websocket

Posted on Thu, 14 Oct 2021 21:31:03 -0400 by affc