npm Babel es6 webpack

1. Introduction

1. What is NPM

NPM, the full name of Node Package Manager, 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, equivalent to Maven on the front end.

2. Installation location of NPM tool

We can easily download js libraries and manage front-end projects through npm.

The location of the npm packages and tools installed by Node.js by default: Node.js directory\
ode_modules

  • In this directory you can see the npm directory. npm itself is a tool managed by the NPM package manager, indicating that Node.js has integrated the npm tool.
#Enter npm -v at the command prompt to view the current npm version
npm -v

2. Use npm to manage projects

1. Create the folder npm

2. Project initialization

#Create an empty folder, enter the folder at the command prompt and execute the command initialization
npm init
#Enter relevant information as prompted. If you use the default value, just press Enter.
#name: project name
#version: project version number
#description: Project description
#keywords: {Array} keywords to facilitate users to search for our projects
#Finally, the package.json file will be generated. This is the package configuration file, which is equivalent to maven's pom.xml.
#We can also modify it later as needed.
#If you want to directly generate the package.json file, you can use the command
npm init -y

2. Modify the npm image

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

It is recommended to use the Taobao NPM mirror http://npm.taobao.org/. The Taobao NPM mirror is a complete npmjs.com mirror. The synchronization frequency is currently once every 10 minutes to ensure that it is synchronized with the official service as much as possible.

Set mirror address:

#After the following configuration, all npm installs in the future will be downloaded through Taobao’s mirror address.
npm config set registry https://registry.npm.taobao.org

#View npm configuration information
npm config list

3. Use of npm install command

#Use npm install to install the latest version of dependent packages,
#Module installation location: project directory\
ode_modules
#The installation will automatically add the package-lock.json file in the project directory. This file helps lock the version of the installation package.
#At the same time, in the package.json file, the dependent package will be added to the dependencies node, similar to <dependencies> in maven
npm install jquery


Projects managed by #npm generally do not carry the node_modules folder when backing up and transferring them.
npm install #Download dependencies according to the configuration in package.json and initialize the project


#If you want to specify a specific version when installing
npm install [email protected]


#devDependencies node: dependency packages during development, dependencies not included when the project is packaged into the production environment
#Use the -D parameter to add dependencies to the devDependencies node
npm install --save-dev eslint
#or
npm install -D eslint


#Global installation
#The location of Node.js globally installed npm packages and tools: User directory\AppData\Roaming\
pm\
ode_modules
#Some command line tools often use global installation.
npm install -g webpack

4. Other commands

#Update package (update to the latest version)
npm update package name
#global update
npm update -g package name

#Uninstall package
npm uninstall package name
#Global uninstall
npm uninstall -g package name

1. Introduction

Babel is a widely used transcoder that can convert ES6 code into ES5 code so that it can be executed in the existing environment.

This means that you can write programs in ES6 now without worrying about whether your existing environment supports it.

2. Installation

Install the command line transcoding tool

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

npm install --global babel-cli

#Check whether the installation is successful
babel --version

3. Use of Babel

1. Initialization project

npm init -y

2. Create file

src/example.js

Here is a piece of ES6 code:

// Before transcoding
// define data
let input = [1, 2, 3]
// Add each element of the array + 1
input = input.map(item => item + 1)
console.log(input)

2. Configuration.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": []
}

The presets field sets the transcoding rules and adds the es2015 rules to .babelrc:

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

3. Install transcoder

Install in project

npm install --save-dev babel-preset-es2015

4. Transcoding

# Write transcoding results to a file
mkdir dist1
# --out-file or -o parameter specifies the output file
babel src/example.js --out-file dist1/compiled.js
# or
babel src/example.js -o dist1/compiled.js

# Transcode the entire directory
mkdir dist2
# --out-dir or -d parameter specifies the output directory
babel src --out-dir dist2
# or
babel src -d dist2

1. Introduction to modularity

1. 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), let alone “module” (module).

2. What is modular development

Traditional non-modular development has the following shortcomings:

  • naming conflict
  • File dependencies

Modular specifications:

  • CommonJS modular specification
  • ES6 Modularity Specification

2. CommonJS module specification

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 the “module” folder

2. Export module

Create common-js modular/four arithmetic operations.js

//Define members:
const sum = function(a,b){
    return parseInt(a) + parseInt(b)
}
const subtract = function(a,b){
    return parseInt(a) - parseInt(b)
}
const multiply = function(a,b){
    return parseInt(a) * parseInt(b)
}
const divide = function(a,b){
    return parseInt(a) / parseInt(b)
}

Export members in a module

//Export members:
module.exports = {
    sum: sum,
    subtract: subtract,
    multiply: multiply,
    divide: divide
}

abbreviation

//Abbreviation
module.exports = {
    sum,
    subtract,
    multiply,
    divide
}

3. Import module

Create common-js modular/import module.js

//Introduce modules, note: the current path must be written ./
const m = require('./four arithmetic operations.js')
console.log(m)

const result1 = m.sum(1, 2)
const result2 = m.subtract(1, 2)
console.log(result1, result2)

4. Run the program

node common-js modularization/introduction module.js

CommonJS uses exports and require to export and import modules.

3. ES6 modular specification

ES6 uses export and import to export and import modules.

1. Export module

Create es6 modular/userApi.js

export function getList() {
    console.log('Get data list')
}

export function save() {
    console.log('save data')
}

2. Import module

Create es6 modular/userComponent.js

//Only take the required methods, separate multiple methods with commas
import { getList, save } from "./userApi.js"
getList()
save()

Note: The program cannot be run at this time because the modularization of ES6 cannot be executed in Node.js. It needs to be edited into ES5 with Babel and then executed.

3. Run the program

node es6 modular-dist/userComponent.js

4. Another way of writing ES6 modularity

1. Export module

Create es6 modular/userApi2.js

export default {
    getList() {
        console.log('Get data list 2')
    },

    save() {
        console.log('Save data 2')
    }
}

2. Import module

Create es6 modular/userComponent2.js

import user from "./userApi2.js"
user.getList()
user.save()

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.

2. Webpack installation

1. Global installation

npm install -g webpack webpack-cli

2. Check the version number after installation

webpack -v

3. Initialization project

1. Create webpack folder

Enter the webpack directory and execute the command

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, 200));

4. JS Packaging

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

The following configuration means: read the content of main.js (entry file) in the src folder in the current project directory, analyze resource dependencies, package the relevant js files, and put the packaged files into the dist folder of the current directory. , the packaged js file is named bundle.js

const path = require("path"); //Node.js built-in module
module.exports = {
    entry: './src/main.js', //Configure entry file
    output: {
        path: path.resolve(__dirname, './dist'), //Output path, __dirname: the path of the current file
        filename: 'bundle.js' //Output file
    }
}

2. Execute compilation command from command line

webpack #There is a yellow warning
webpack --mode=development #No warning
#After execution, view bundle.js which contains the contents of the above two js files and activates code compression.

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

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

Run npm command to perform packaging

npm run dev

3. Create index.html

in the webpack directory

Reference bundle.js

<body>
    <script src="dist/bundle.js"></script>
</body>

4. View index.html in the browser

5. 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 a loader for conversion.

Loader can be understood as a converter between modules and resources.

First we need to install the relevant Loader plug-in. css-loader loads css into javascript; style-loader allows javascript to understand css.

npm install --save-dev style-loader css-loader

2. Modify webpack.config.js

const path = require("path"); //Node.js built-in module
module.exports = {
    //...,
    output:{},
    module: {
        rules: [
            {
                test: /\.css$/, //Packaging rules are applied to files ending with css
                use: ['style-loader', 'css-loader']
            }
        ]
    }
}

3. Create style.css in the src folder****

body{
    background:pink;
}

4. Modify main.js

Introduce style.css on the first line

require('./style.css');

5. View index.html in the browser

See if the background turns pink?

1. vue-element-admin

1. Introduction

vue-element-admin is a backend management system integration solution based on element-ui.

**Function: **https://panjiachen.github.io/vue-element-admin-site/zh/guide/#Function

**GitHub address: **https://github.com/PanJiaChen/vue-element-admin

Online preview of the project: https://panjiachen.gitee.io/vue-element-admin

2. Installation

# Decompress the compressed package
# Enter directory
cd vue-element-admin-master

# Install dependencies
npm install

# start up. After execution, the browser automatically pops up and accesses http://localhost:9527/
npm rundev

2. vue-admin-template

1. Introduction

vueAdmin-template is a set of background management system basic templates (at least streamlined version) based on vue-element-admin, which can be used as a template for secondary development.

**GitHub address: **https://github.com/PanJiaChen/vue-admin-template

**Suggestion:** You can carry out secondary development based on vue-admin-template and use vue-element-admin as a toolbox to determine what functions you want. Or just copy the component from vue-element-admin.

2. Installation

# Decompress the compressed package
# Enter directory
cd vue-admin-template-master

# Install dependencies
npm install

# start up. After execution, the browser automatically pops up and accesses http://localhost:9528/
npm rundev

1. Project creation and basic configuration

1. Create a project

Rename vue-admin-template-master to guli-admin

2. Modify project information

package.json

{
    "name": "guli-admin",
    ...
    "description": "Guli Academy backend management system",
    "author": "Helen <[email protected]>",
    ...
}

3. If you need to modify the port number

Modify in config/index.js

port: 9528

4. Project directory structure

.
├── build // Build script
├── config // global configuration
├── node_modules // Project dependent modules
├── src //Project source code
├── static // static resources
└── package.jspon // Project information and dependency configuration
src
├── api // Various interfaces
├── assets // Pictures and other resources
├── components // Various public components, non-public components are maintained under their respective views
├── icons //svg icon
├── router // routing table
├── store // store
├── styles // various styles
├── utils // Public tools, non-public tools, maintained under their respective views
├── views // Various layouts
├── App.vue //***top-level component of the project***
├── main.js //***Project entry file***
└── permission.js //Authentication entrance

5. Run the project

npm run dev

2. Login page modification

src/views/login/index.vue (login component)

4 lines

<h3 class="title">Guli Academy Backend Management System</h3>

Line 28

<el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
    Log in
</el-button>

3. Sporadic page modifications

1**, title**

index.html (html entry of the project)

<title>Guli Academy Backend Management System</title>

Hot deployment function after modification, browser automatically refreshes

2. International settings

Open src/main.js (js entry of the project), line 7, change the language to zh-CN, use the Chinese locale, for example: date and time component

import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n

3, icon

Copy favicon.ico to the root directory

4. Navigation bar text

src/views/layout/components (layout components of the current project)

src/views/layout/components/Navbar.vue

13 lines

<el-dropdown-item>
    front page
</el-dropdown-item>

Line 17

<span style="display:block;" @click="logout">Exit</span>

5. Breadcrumb text

src/components (common components that can be reused in many projects)

src/components/Breadcrumb/index.vue

Line 38

meta: { title: 'Home' }

4. Eslint syntax specification check

1. Introduction to ESLint

JavaScript is a dynamic, weakly typed language that is prone to errors during development. Because there is no compiler, finding bugs in JavaScript code often requires constant tweaking during execution.

ESLint is a checking tool for syntax rules and coding style, which can be used to ensure that code with correct syntax and uniform style is written. Let programmers find problems during the coding process rather than during the execution process.

2. Grammar rules

ESLint has some built-in rules, which can also be customized during use.

The grammatical rules of this project include: two-character indentation, single quotes must be used, double quotes cannot be used, semicolons cannot be written after statements, there must be a blank line between code segments, etc.

3. Confirm to enable grammar checking

Open config/index.js and configure whether to enable syntax checking

useEslint: true,

You can turn off syntax checking, but it is recommended to turn it on to develop good programming habits.

4. ESLint plug-in installation

The ESLint plug-in for vs code can help us automatically organize the code format

5. Plug-in extension settings

Select “Settings” in the lower left corner of vs code, open the VSCode configuration file, and add the following configuration

"files.autoSave": "off",
"eslint.validate": [
  "javascript",
  "javascriptreact",
  "vue-html",
  {
    "language": "vue",
    "autoFix": true
  }
],
"eslint.run": "onSave",
"eslint.autoFixOnSave": true