Server side modularity specification

1. commonJS

  • Modules are divided into single file modules and packages
  • Module member exports: module.exports and exports
  • Module member import: require(‘ module identifier ‘)

Unified modular specification -ES6 modular

ES6 modular specification is a common modular development specification for browser and server.

As defined in the ES6 modular specification:

  • Each JS file is an independent module
  • Import module members using the import keyword
  • Expose module members using the export keyword

Experience ES6 modularity with Babel in Node.js

  1. npm install –save-dev @babel/core @babel/cli @babel/preset-env @babel/node
  2. npm install –save @babel/polyfill
  3. The project and directory create the file babel.config.js
  4. The babel.config.js file contains the following code
  5. Execute the code via NPX babel-node index.js
Const presets = [["@babel/env", {targets: {edge: "17", Firefox: "60", Chrome: "67", Safari: "11.1"}}]]; module.exports = { presets };Copy the code

The basic syntax for ES6 modularity

Default export vs. default import

  • Default Export syntax Export default Members to be exported by default
// define private members a and c let a = 10; let c = 20; // let d = 30; Function show() {} export default {a, d, show}Copy the code
  • Default import syntax import accept name from ‘module identifier’
Import m1 from './m1.js' console.log(m1) // {a:10, c: 20, show: [Function: show]}Copy the code

Note: export default can only be used once in each module, otherwise an error will be reported!

Export on demand versus import on demand

  • Export let s1 = 10
  • Import {s1} from ‘module identifier’
Import {s1, s2 as ss2, Say} from './m1.js' console.log(s1) aaa console.log(ss2) CCC console.log(say) [Function: say]Copy the code
// The current file module is m1.js // Export variable s1 export let s1 = 'AAA' // Export variable s2 export let s2 = 'CCC' // Export method say export on demand function say = funciton () {}Copy the code

Note: Multiple on-demand exports can be implemented within each module

Import and execute the module code directly

Sometimes, when we just want to execute the code in a module and don’t need to get exposed members of the module, we can import and execute the module code directly.

// Execute a for loop in the current module for(let I = 0; i < 3; i++) { console.log(i) }Copy the code
// Import './m2.js' directly and execute module codeCopy the code

webpack

  • Webpack is a popular front-end project building tool (packaging tool) that addresses the dilemmas of current Web development
  • Webpack provides friendly module support, as well as code compression and confusion, dealing with JS compatibility problems, performance optimization and other powerful functions, so that programmers put the focus of work on specific function implementation, improve the development efficiency and project maintainability.

The current dilemma of Web development

  • File dependencies are complex
  • Static resource requests are inefficient
  • Modular support is not friendly
  • Browsers are less compatible with advanced Javascript features

Basic use of Webpack

1. Create list interlaced color change items
  1. Create a blank directory for the project and run NPM init -y to initialize the package.json configuration file
  2. Create a new SRC source directory
  3. Create a new SRC -> index.html home page
  4. Initialize the basic structure of the home page
  5. Run NPM install jquery -$to install jquery
  6. Through the form of modular, achieve interlaced color effect
2. Install and configure WebPack in the project
  1. Run the NPM install webpack webpack-cli -d command to install webpack-related packages
  2. In the project root, create a webpack configuration file called webpack.config.js
  3. In the webPack configuration file, initialize the following basic configuration:
Module. exports = {mode:'development' // mode is used to specify build mode.Copy the code
  1. Under the scripts node in the package.json configuration file, add the following dev script:
"Script ": {"dev": "webpack" // scripts under the script node can be executed by NPM run}Copy the code
  1. Run the NPM run dev command in the terminal to start webpack for project packaging
3. Configure the inlet and outlet for packing

The default convention in the 4.x version of Webpack:

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

If you want to change the entry and exit of packaging, you can add the following configuration information in webpack.config.js:

Const path = require('path') // imports module.exports = {entry: Path. join(__dirname, './ SRC /index.js'), // Package entry file output: {path: Path. join(__dirname, './dist'), // output file path filename: 'bundle.js' // output filename}}Copy the code
4. Configure the webPack automatic packaging function
  1. Run the NPM install webpack-dev-server -d command to install the tool that supports automatic project packaging
  2. Modify the dev command in package.json -> scripts as follows

Pay special attention to the pit

  • Error: Cannot find module ‘webpack-cli/bin/config-yargs’
"Script ": {"dev": "webpack serve" // script node under the script, can be executed by NPM run}Copy the code
  1. /bundle.js SRC -> index.html /bundle.js /bundle.js
  2. Run the NPM run dev command to repackage
  3. Visit http://localhost:8080 in your browser to see the effect of automatic packaging

Note:

  • Webpack Serve launches a real-time packaged HTTP server
5. Configure html-webpack-plugin to generate a preview page
  1. Run NPM install html-webpack-plugin -d to install the plug-in that generates the preview page
  2. Modify the webpack.config.js header and add the following configuration information:
// Import the plugin that generated the preview page, get a constructor function // import the plugin that generated the preview page, Const HtmlWebpackPlugin = require('html-webpack-plugin') const htmlPlugin = new HtmlWebpackPlugin({//) Template: './ SRC /index.html', // specify the template file to use filename: 'index.html' // specify the name of the generated file, which exists in memory and is not displayed in the directory})Copy the code
  1. Modify the configuration objects exposed in the webpack.config.js file and add the following configuration nodes:
Module.exports = {plugins: [htmlPlugin] // plugins array is a list of plugins used during webpack}Copy the code
6. Set parameters related to automatic packaging
// package. Json configuration // --open Automatically open browser page after package completion // --host configure IP address // --port configure port "script": {"dev": "Webpack-dev-server --open --host 127.0.0.1 --port 8888"},Copy the code

Webpack loader

1. Use loader to package non-JS modules

By default, Webpack only handles modules ending in the.js suffix. Webpack cannot process other modules whose names do not end with.js suffix by default. You need to call loader to pack them normally, otherwise an error will be reported.

Loader can help WebPack handle specific file modules, such as:

  • Less-loader can package files related to processing.less
  • Sass-loader can package files that handle.scss
  • Url-loader packages and processes files related to URL paths in the CSS

Basic use of loaders in Webpack

  • css
  • less
  • scss
  • javascript
  • image/font
  • vue
Package and process CSS files
  1. Run the NPM I style-loader css-loader -d command to install the loader that processes CSS files
  2. In the module -> rules array of webpack.config.js, add the loader rule as follows:
Module: {rules: [{test: /\.css$/, use: ['style-loader', 'css-loader']}]}Copy the code

Test indicates the matched file type, and use indicates the loader to be invoked

Note:

  • The loader order specified in the use array is fixed
  • Multiple Loaders are invoked in the following order: from back to front
Package processing less
  1. Run the NPM I less-loader less -d command
  2. In the module -> rules array of webpack.config.js, add the loader rule as follows:
Module: {rules: [{test: /\. Less $/, use: ['style-loader', 'css-loader', 'less-loader}Copy the code
Package and process SCSS files
  1. Run the NPM I sass-loader node-sass -d command
  2. In the module -> rules array of webpack.config.js, add the loader rule as follows:
Module: {rules: [{test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader']}]}Copy the code
Configure postCSS To automatically add the CSS compatible prefixes

Some CSS3 statements have compatibility problems in ie earlier browsers (such as ::placeholder{color:red}), so you need to add compatibility prefix to CSS statements, but it is more difficult to add it yourself, WebPack can solve this problem.

  1. Run the NPM I postcss-loader autoprefixer -d command
  2. Create the postcss configuration file postcss.config.js in the project root directory and initialize the following configuration:
Module. Exports = {plugins: [autoprefixer] // import plugins from module. Exports = {plugins: [autoprefixer] // import plugins from module.Copy the code
  1. In the webpack.config.js module -> rules array, modify the CSS loader rules as follows:
 module: {
     rules: [
         { test:/\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }
     ]
 }
Copy the code
Package the image and font files in the stylesheet
  1. Run the NPM I url-loader file-loader -d command
  2. In the module -> rules array of webpack.config.js, add the loader rule as follows:
module: {
     rules: [
         { 
         test: /\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/, 
         use: 'url-loader?limit=16940'
         }
     ]
 }
Copy the code
  • Among them? The loader parameters follow.
  • Limit specifies the size of an image, in bytes. Only images smaller than limit size will be converted to Base64 (for faster image loading).
Package handles advanced syntax in JS files
  1. NPM I babel-loader @babel/ core@babel/run-time -d
  2. NPM I @babel/preset-env @babel/plugin- transform-runtime@babel /plugin-proposal-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-proposal-class-properties']}Copy the code
  1. Add loader rules to webpack.config.js module -> rules array as follows:
// exclude indicates that babel-loader does not need to process js files in node_modules {test: /\. Js $/, use: 'babel-loader', exclude: /node_modules/ }Copy the code

Vue single file component

Problems and solutions for traditional components

The problem
  1. Globally defined components must have unique component names
  2. String templates lack syntactic highlighting and require ugly \ when HTML has multiple lines
  3. Not supporting CSS means that CSS is conspicuously missing when HTML and JavaScript are componentized
  4. No build step restrictions, only HTML and ES5 JavaScript, not preprocessing (e.g. Babel)
The solution

Vue provides a solution to the problem of passing components by using Vue single-file components.

Basic usage of Vue single file components

The composition structure of a single file component
  • The template area of the template component
  • Script business logic area
  • Style area
<template> <! </template> <script> // export default {data: () {return {}}, / / private data the methods: {} / / / / processing function... </script> <style scoped>Copy the code
Webpack configures the loader for vUE components
  1. Run the NPM I vue-loader vue-template-compiler -d command
  2. In the webpack.config.js configuration file, add the following configuration items for vue-loader:
Export.exports = {module: {rules: [//... export.exports = {rules: [//... /\.vue$/, loader: 'VueLoaderPlugin'}]}, plugins: [//... }Copy the code

Use VUE in webPack projects

  1. Run NPM I vue — S to install vUE
  2. In the SRC -> index.js entry file, import the Vue constructor by importing Vue from ‘Vue’
  3. Create an instance object of vUE and specify the EL region to control
  4. Render the App root with the render function
Import Vue from 'Vue' // 2. /components/ app. vue' const vm = new vue ({// 3. Specify the page area that the vm instance controls el: '#app', // 4. Render: h => h(App)}Copy the code

Webpack is packaged and distributed

Before going online, you need to package the application as a whole through Webpack. You can configure the packaging command through package.json file:

Here are the pit

The packaged publishing command is no longer webpack -p but now webpack –mode Production

// This command loads the webpack.config.js configuration file "scripts" in the root directory of the project by default: {// The command "build" for packaging: Dev: "webpack-dev-server --open --host 127.0.0.1 --port 3000",}Copy the code

15. Vue scaffolding

Vue scaffolding can quickly generate the architecture underlying a Vue project.

A. Install version 3.x Vue scaffolding:

npm install -g @vue/cli
Copy the code

B. Create Vue project based on 3.x version scaffolding:

  1. Create a Vue project using the command
  • Command: vue create my-project
  • Select Manually select Features to create a project
  • Check features can be checked with a space.
  • Whether to select the route in historical mode: n
  • ESLint Select ESLint + Standard config
  • When to validate ESLint syntax: Lint on save
  • In dedicated config files, Babel, postcss, etc.
  • Whether to save as a template: n
  • Which tool installation package to use: NPM
  1. Create Vue projects based on the UI interface
  • Command: vue UI
  • Configure project information in the Create project page that opens automatically.
  1. Create a Vue project based on the old 2.x template
  • npm install -g @vue/cli-init
  • vue init webpack my-project

C. Analyze the project structure generated by Vue scaffolding

Node_modules: dependency package directory public: static resource directory SRC: source directory SRC /assets: resource directory SRC /components: Component directory SRC/app. vue: root component SRC /main.js: entry js SRC /router.js: route js babel.config.js: Babel configuration file.eslintrc.js:Copy the code

16. Custom configuration of Vue scaffolding

A. Using package.json [not recommended]

        "vue":{
            "devServer":{
                "port":"9990",
                "open":true
            }
        }
Copy the code

B. Use a separate configuration file to create vue.config.js

        module.exports = {
            devServer:{
                port:8888,
                open:true
            }
        }
Copy the code

17. Basic use of element-UI

Element-ui: A set of 2.0 based desktop component libraries

Elem. IO /#/ zh-cn

NPM install element-ui -s B Import using:

    import ElementUI from "element-ui";
    import "element-ui/lib/theme-chalk/index.css";
    
    Vue.use(ElementUI)
Copy the code