On the sixth day of vue, front-end engineering webpack, babel, vue single component, vue scaffold and element UI

--------------Modularization related specifications------------------

1.1 modular overview

Main problems of traditional development mode

  1. name conflict
  2. File dependency

Solve the above problems through modularization

  1. Modularization is to encapsulate a single function into a module (file). Modules are isolated from each other, but internal members can be exposed through specific interfaces or rely on other modules
  2. Benefits of modular development: facilitate code reuse, improve development efficiency, and facilitate later maintenance

1.2 browser side modular specification

  1. AMD
    Require.js (http://www.requirejs.cn/)
  2. CMD
    Sea.js (https://seajs.github.io/seajs/docs/)

1.3 server side modular specification

1. CommonJS

  1. Modules are divided into single file modules and packages
  2. Module member export: module Exports and exports
  3. Module member import: require('module identifier')

1.4 unified modular specification – ES6 modularization

Before the birth of ES6 modular specification, the Javascript community has tried and proposed AMD, CMD, CommonJS and other modular specifications.

However, the modular standards proposed by these communities still have some differences and limitations. They are not the general modular standards for browsers and servers, such as:

  1. AMD and CMD are suitable for browser side Javascript modularization
  2. CommonJS is suitable for server-side Javascript modularization

Therefore, the ES6 syntax specification defines the ES6 modular specification at the language level, which is a general modular development specification for browser and server.

Defined in ES6 modular specification:

  1. Each js file is a separate module
  2. Import module members use the import keyword
  3. Expose module members using the export keyword

1.5 Node. Experience ES6 modularity through babel in JS

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
  2. npm install --save @babel/polyfill
  3. Create directory with project.bel config. js
  4. babel. config. The contents of the JS file are shown in the code on the right
  5. Through NPX Babel node index JS execution code
	 const presets = [
		 ["@babel/env", {
			 targets: {
				 edge: "17",
				 firefox: "60",
				 chrome: "67",
				 safari: "11.1"
			 }
		 }]
	 ];
	 module.exports = { presets };

1.5 basic syntax of ES6 modularization

1. Default export and default import

  1. Default export syntax export default the default exported member
  2. Default import syntax import receive name from 'module identifier'

Note: in each module, only one export default is allowed, otherwise an error will be reported!

	// Import module members
	 import m1 from './m1.js'
	 
	 console.log(m1)
	 // The printout result is:
	 // { a: 10, c: 20, show: [Function: show] }
	// The current file module is M1 js
	
	// Define private members a and c
	let a = 10
	let c = 20
	// Variable d cannot be accessed by the outside world because it is not exposed
	let d = 30
	function show() {}
	
	// Expose the private members in this module for use by other modules
	export default {
		 a,
		 c,
		 show
	}

2. Export on demand and import on demand

  1. On demand export syntax export let s1 = 10
  2. On demand import syntax import {S1} from 'module identifier'

Note: multiple on-demand exports can be used in each module

 // Import module members
 import { s1, s2 as ss2, say } from './m1.js'
 console.log(s1) // Printout aaa
 console.log(ss2) // Printout ccc
 console.log(say) // Printout [Function: say]
// The current file module is M1 js

// Export variable s1 outward on demand
export let s1 = 'aaa' 
// Export variable s2 outward as needed
export let s2 = 'ccc'
// Export method say out on demand
export function say = function() {}

3. Import and execute module code directly

Sometimes, we just want to execute the code in a module without getting the exposed members in the module. At this time, we can directly import and execute the module code.

 // Import and execute module code directly
 import './m2.js'
// The current file module is m2 js

// Execute a for loop operation in the current module
for(let i = 0; i < 3; i++) {
 console.log(i)
}

------------------------- webpack -----------------------

2.1 difficulties faced by current Web development

  1. Complex File Dependencies
  2. Low efficiency of static resource request
  3. Modular support is not friendly
  4. Browsers are less compatible with advanced Javascript features
  5. etc...

2.1 overview of webpack

webpack is a popular front-end project construction tool (packaging tool), which can solve the difficulties faced in the current web development.
webpack provides friendly modular support, as well as powerful functions such as code compression confusion, handling js compatibility problems and performance optimization, so that programmers can focus on the specific function implementation, and improve the development efficiency and maintainability of the project.

At present, most front-end projects in enterprises are packaged and built based on webpack.

2.2 basic use of webpack

1. Create list interlaced color change items

  1. Create a new project blank directory and run the npm init – y command to initialize the package management configuration file package json
  2. New src source directory
  3. New SRC - > index HTML home page
  4. Initialize the basic structure of the home page
  5. Run the npm install jquery – S command to install jQuery
  6. Through the modular form, the color change effect of list interlacing is realized

2. Install and configure webpack in the project

  1. Run the NPM install webpack webpack cli – D command to install the webpack related packages
  2. In the root directory of the project, create a file named webpack.com config. Webpack configuration file of JS
  3. In the configuration file of webpack, initialize the following basic configuration:
module.exports = {
 mode: 'development' // Mode is used to specify the build mode
}
  1. In package Under the scripts node in the JSON configuration file, the new dev script is as follows:
"scripts": {  // Note the json format
	"dev": "webpack" // Scripts under the script node can be executed through npm run
}
  1. Run the npm run dev command in the terminal to start webpack for project packaging.

3. Configure the inlet and outlet of packaging
webpack 4 Default conventions in X version:

  1. The packaged entry file is SRC - > index js
  2. The packaged output file is dist - > main js

If you want to modify the entry and exit of the package, you can use webpack config. JS adds the following configuration information:

const path = require('path') // Import node JS module dedicated to operation path
module.exports = {
	 entry: path.join(__dirname, './src/index.js'), // Path to package entry file
	 output: {
		 path: path.join(__dirname, './dist'), // Storage path of output file
		 filename: 'bundle.js' // The name of the output file
	 } 
}

4. Configure the automatic packaging function of webpack

  1. Run the NPM install webpack dev server – D command to install tools that support automatic project packaging
  2. Modify package The dev command in JSON - > scripts is as follows:
"scripts": {
 "dev": "webpack-dev-server" // Scripts under the script node can be executed through npm run
}
  1. Set SRC - > index In HTML, the reference path of script script is modified to "/ bundle. JS“
  2. Run the npm run dev command to repack
  3. Access in browser http://localhost:8080 Address and view the effect of automatic packaging

be careful:

  1. Webpack dev server will start a real-time packaged http server
  2. The output file generated by webpack dev Server package is placed in the project root directory by default, and it is virtual and invisible

5. Configure HTML webpack plugin to generate preview page

  1. Run the NPM install HTML webpack plugin – D command to install the plug-in that generates the preview page
  2. Modify webpack config. JS file header area, add the following configuration information:
// Import the plug-in that generates the preview page and get a constructor
const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebpackPlugin({ // Create an instance object of the plug-in
 template: './src/index.html', // Specify the template file to use
 filename: 'index.html' // Specifies the name of the generated file, which exists in memory and is not displayed in the directory
})
  1. Modify webpack config. JS file, add the following configuration nodes:
module.exports = {
 plugins: [ htmlPlugin ] 
 // The plugins array is a list of plug-ins that will be used during webpack packaging
}

6. Configure parameters related to automatic packaging

	 // package. Configuration in JSON
	 // --open automatically opens the browser page after packaging
	 // --host configure IP address
	 // --Port configuration port
	 "scripts": {
		 "dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888"
	 },

2.3 loader in webpack

1. Package non js modules through loader

In the actual development process, webpack can only be packaged and processed by default js suffix end of the module, other non Modules ending in js suffix cannot be handled by webpack by default. You need to call the loader loader to package normally, otherwise an error will be reported!

The loader loader can assist webpack in packaging and processing specific file modules, such as:

  1. less loader can be packaged less related documents
  2. Sass loader can be packaged scss related documents
  3. url loader can package and process files related to url path in css

2.4 basic usage of loader in webpack

1. Package css files

  1. Run the NPM I style loader css loader - D command to install the loader that handles css files
  2. On webpack config. In the module - > rules array of JS, add the loader rule as follows:
 // Matching rules for all third-party file modules
 	module: {
		 rules: [
			 { test: /\.css$/, use: ['style-loader', 'css-loader'] }
 		]
	 }

Where, test represents the matching file type, and use represents the corresponding loader to be called
be careful:

  1. The order of loader s specified in the use array is fixed (so pay attention to the order)
  2. The calling sequence of multiple loader is: calling from back to forward.

2. Package and process less files

  1. Run the NPM I less loader less - D command
  2. On webpack config. In the module - > rules array of JS, add the loader rule as follows:
 // Matching rules for all third-party file modules
	 module: {
		 rules: [
			 { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }
		 ]
	 }

3. Package scss files

  1. Run the NPM I sass loader node sass - D command
  2. On webpack config. In the module - > rules array of JS, add the loader rule as follows
 // Matching rules for all third-party file modules
	 module: {
		 rules: [
			 { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }
		 ]
	 }

4. Configure postCSS to automatically add the compatible prefix of css

  1. Run the NPM I postcss loader autoprefixer - D command
  2. Create the configuration file of postcss in the root directory of the project config. JS and initialize the following configuration:
 const autoprefixer = require('autoprefixer') // Import a plug-in that automatically prefixes
 module.exports = {
	 plugins: [ autoprefixer ] // Mount plug-in
 }
  1. On webpack config. In the module - > rules array of css, modify the loader rule of css as follows:
 module: {
 	rules: [
		 { test:/\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }
	 ]
 }

5. Package the pictures and font files in the style sheet

  1. Run the NPM I URL loader file loader - D command
  2. On webpack config. In the module - > rules array of JS, add the loader rule as follows:
 module: {
	 rules: [
		 { 
			 test: /\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/, 
			 use: 'url-loader?limit=16940'
		 }
	 ]
 }

Among them? Then comes the parameter item of loader.
Limit is used to specify the size of the picture in bytes. Only pictures smaller than the limit size will be converted to base64 pictures

6. Package and process the high-level syntax in js files

  1. Install package related to babel converter: NPM I babel loader @ babel / core @ babel / runtime - D
  2. Install package related to babel syntax plug-in: NPM I @ babel / preset env @ babel / plugin transformruntime @ babel / plugin proposed class properties – D
  3. In the project root directory, create the babel configuration file babel config. JS and initialize the basic configuration as follows:
 module.exports = {
	 presets: [ '@babel/preset-env' ],
	 plugins: [ '@babel/plugin-transform-runtime', '@babel/plugin-proposalclass-properties' ]
 }
  1. On webpack config. In the module - > rules array of JS, add the loader rule as follows
 // exclude is an exclusion item, indicating that Babel loader does not need to process node_ js file in modules
 { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }

----------------------Vue single file component-------------------------

3.1 problems and solutions of traditional components

1. Problems

  1. Globally defined components must ensure that the names of components are not repeated
  2. The string template lacks syntax highlighting. When there are multiple lines of HTML, it needs to use ugly\
  3. Not supporting CSS means that CSS is obviously missing when HTML and JavaScript are componentized
  4. There are no restrictions on the construction steps. Only HTML and ES5 JavaScript can be used, but not preprocessors (such as Babel)

2. Solutions
Vue provides a solution to the problem of traditional components - using Vue single file components.

3.2 basic usage of Vue single file component

Composition structure of single file components

  1. Template area of template component
  2. script business logic area
  3. style area
	 <template>
		 <!-- Used here to define Vue Template content of component -->
	 </template>
	 
	 <script>
	 // The logic used to define Vue business components here
		 export default {
			 data: () { return {} }, // Private data
			 methods: {} // Processing function
		 // ...  Other business logic
		 }
	 </script>
	 
	 <style scoped>
	 /* This is used to define the style of the component */
	 </style>

3.3 loader for configuring vue components in webpack

  1. Run the NPM I Vue loader Vue template compiler - D command
  2. On webpack config. JS configuration file, add the following configuration items of Vue loader
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
	 module: {
		 rules: [
		 // ...  Other rules
			 { test: /\.vue$/, loader: 'vue-loader' }
		 ]
	 },
	 plugins: [
		 // ...  Other plug-ins
		 new VueLoaderPlugin() // Please make sure to introduce this plug-in!
	 ] 
}

3.4 using vue in webpack project

  1. Run npm i vue – S install vue
  2. In SRC - > index JS entry file, import vue constructor by importing vue from 'vue'
  3. Create an instance object of vue and specify the el area to control
  4. Render App root component through render function
// 1. Import Vue constructor
import Vue from 'vue'
// 2. Import App root component
import App from './components/App.vue'

const vm = new Vue({
 // 3. Specify the page area to be controlled by the vm instance
 	el: '#app',
 // 4. Render the specified components into the el area through the render function
	 render: h => h(App)
})

3.5 packaging and publishing of webpack

Before going online, you need to package the application as a whole through webpack. You can use package JSON file configuration packaging command:

 // In package Configure webpack packaging command in JSON file
 // This command loads the webpack.com in the root directory of the project by default config. JS configuration file
 "scripts": {
	 // Commands for packaging
	 "build": "webpack -p",
 	// Commands for development and debugging
	 "dev": "webpack-dev-server --open --host 127.0.0.1 --port 3000",
 },

-----------------------Vue scaffold-------------------------

4.1 basic usage of Vue scaffold

Vue scaffold is used to quickly generate Vue project infrastructure. Its official website address is: https://cli.vuejs.org/zh/

Use steps

  1. Installation 3 Vue scaffold version x: npm install -g @vue/cli

Based on 3 Create vue project with version x scaffold

  1. Create a new vue project based on the interactive command line
    vue create my-project

  2. Create a new vue project based on the graphical interface
    vue ui (this is the best)

  3. Based on 2 Old template of X, create old vue project
    npm install -g @vue/cli-init
    vue init webpack my-project

4.2 project structure analysis generated by Vue scaffold

	node_modules         Dependent package directory
	public               Static resource directory
	src                  Component source code directory
	babel.config.js      babel configuration file
	wait....

4.3 user defined configuration of Vue scaffold

  1. Through package JSON configuration project (let the page open and run automatically)
 // Must be json syntax compliant
 "vue": {
 	"devServer": {
		 "port": "8888",
		 "open" : true
	 }
 },

Note: this configuration is not recommended. Because package JSON is mainly used to manage the configuration information of the package; In order to facilitate maintenance, it is recommended to define the configuration related to vue scaffold separately to vue config. JS configuration file.

  1. Configure items through a separate profile (only one of 1 and 2 can be selected for use)
1. Create a file in the following directory of the project vue.config.js
2. Make relevant configuration in this file to overwrite the default configuration

 // vue.config.js
	 module.exports = {
		 devServer: {
			 port: 8888
		 }
	 }

------------------------ Element-UI --------------------------

Element UI: a set of desktop component library based on Vue 2.0 for developers, designers and product managers. The official website address is: http://element-cn.eleme.io/#/zh-CN

1. Manual installation based on command line mode

  1. Install dependency package NPM I element UI – S
  2. Import element UI related resources
 // Import component library
 import ElementUI from 'element-ui';
 // Import component related styles
 import 'element-ui/lib/theme-chalk/index.css';
 // Configuring Vue plug-ins
 Vue.use(ElementUI);

2. Automatic installation based on graphical interface

  1. Run the vue ui command to open the graphical interface
  2. Enter the specific project configuration panel through Vue project manager
  3. Click plug-in - > Add plug-in to enter the plug-in query panel
  4. Search for Vue cli plugin element and install it
  5. Configure plug-ins to realize on-demand import, so as to reduce the volume of packaged items

Keywords: Vue

Added by nosmasu on Thu, 10 Feb 2022 20:45:31 +0200