Vue Learning – Modular development

Multiple JS files cause problems

Global variables have the same name, causing multiple developers to modify variables by others

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
  </head>
  <body>

    <script src="aaa.js"></script>
    <script src="bbb.js"></script>
    <script src="mmm.js"></script>
  </body>
</html>
Copy the code
// Xiaoming development
// aaa.js
var name = 'xiaoming';
var age = 22;

function sum(num1, num2) {
  return num1 + num2;
}

var flag = true;

if (flag) {
  console.log(sum(10.20)); / / 30
}
Copy the code
// Xiaohong development
// bbb.js
var name = 'xiaohong';
var flag = false;

console.log(name); // xiaohong
Copy the code
// mmm.js
if (flag) {
  console.log('Xiao Ming is a genius'); // This will not be printed
}
Copy the code

Anonymous function solution (original prototype)

Functions have their own scope

// Xiaoming development
// aaa.js
;
var moduleA = (function() {

  var obj = {};

  var name = 'xiaoming';
  var age = 22;

  function sum(num1, num2) {
    return num1 + num2;
  }

  var flag = true;

  if (flag) {
    console.log(sum(10.20));
  }

  obj.flag = flag;
  obj.sum = sum;

  console.log(obj);

  returnobj; }) ();Copy the code
// Xiaohong development
// bbb.js
;
var moduleB = (function() {
  var obj = {};
  var name = 'xiaohong';
  var flag = false;

  console.log(name);

  obj.flag = flag;
  returnobj; }) ();Copy the code
// mmm.js; (function() {
  if (moduleA.flag) {
    console.log('Xiao Ming is a genius'); // Can print normally
  }
})();
Copy the code

Common modular specifications

  • CommonJs

    Two core modules of modularity: export and import

    Export in CommonJs

    module.exports = {
    	flag: true.test(a, b) {
        return a + b;
      },
      demo(a, b) {
        returna * b; }}Copy the code

    Import in CommonJs

    let { test, demo, flag } = require('moduleA');
    // moduleA is the path to the exported file
    Copy the code
  • AMD

  • CMD

  • The Modules in ES6

    Two keywords are added in ES6: export import

Index.html

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
  </head>
  <body>// Add type="module"<script src="aaa.js" type="module"></script>
    <script src="bbb.js" type="module"></script>
    <script src="mmm.js" type="module"></script>
  </body>
</html>
Copy the code

aaa.js

// Xiaoming develops aaA.js
let name = 'xiaoming';
let age = 18;
let flag = true;

function sum(num1, num2) {
  return num1 + num2;
}

if (flag) {
  console.log(sum(10.20));
}

Export method 1
export {
flag, sum
}

// 2. Export 2
export var num1 = 1000;
export var height = 1.88;

// 3. Export functions/classes
export function mul(num1, num2) {
  return num1 * num2;
}

export class Person {
  run() {
    console.log('run'); }}// 4. export default
// In some cases, a module contains a function that we do not want to name and let the importer name it. Export Default can be used in this case
// Export default can exist only one module
const address = 'beijing';
export default address;

Copy the code

bbb.js

// Xiaohong develops bbb.js
let name = 'little red';
let flag = false;
Copy the code

mmm.js

import { flag, sum } from './aaa.js'

if (flag) {
  console.log('Xiao Ming is a genius');
  console.log(sum(100 , 200));
} 

import { num1, height } from './aaa.js'

console.log('num1 ', num1);
console.log('height ', height);


import { mul, Person } from './aaa.js'
console.log(mul(100.100));

const p = new Person();
p.run();

import add from './aaa.js'
console.log(add);

/ / the wildcard
import * as aaa from './aaa.js'
console.log(aaa.flag);
console.log(aaa.height);

Copy the code

webpack

Know webpack

Modular packaging tool

Modular:

One of the cores of WebPack is to help us do modular development and to help us deal with dependencies between modules

And not only js files, our CSS, images, JSON files, etc. can be used as modules in Webpack

Packaging:

Is the webpack of various resource modules into one or more packages

In the process of packaging, resources can be processed, such as compressing images, converting SCSS to CSS, converting ES6 syntax to ES5 syntax and so on

The installation of the webpack

// Check the node version. Node -v webpack NPM install [email protected] -gCopy the code

Webpack start

main.js

const { sum, mul } = require('./mathUtil.js');

console.log(sum(20.30));
console.log(mul(20.30));
Copy the code

mathUtil.js

function sum(num1, num2) {
  return num1 + num2;
}

function mul(num1, num2) {
  return num1 * num2;
}

module.exports = {
  sum, mul
}
Copy the code

The webpack command

webpack ./src/main.js ./dist/bundle.js
Copy the code

Index.html

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
  </head>
  <body>

    <script src="./dist/bundle.js"></script>
  </body>
</html>
Copy the code

Bundled bundle.js

/ * * * * * * / (function(modules) { // webpackBootstrap
/ * * * * * * / 	// The module cache
/ * * * * * * / 	var installedModules = {};
/ * * * * * * /
/ * * * * * * / 	// The require function
/ * * * * * * / 	function __webpack_require__(moduleId) {
/ * * * * * * /
/ * * * * * * / 		// Check if module is in cache
/ * * * * * * / 		if(installedModules[moduleId]) {
/ * * * * * * / 			return installedModules[moduleId].exports;
/ * * * * * * / 		}
/ * * * * * * / 		// Create a new module (and put it into the cache)
/ * * * * * * / 		var module = installedModules[moduleId] = {
/ * * * * * * / 			i: moduleId,
/ * * * * * * / 			l: false./ * * * * * * / 			exports: {}
/ * * * * * * / 		};
/ * * * * * * /
/ * * * * * * / 		// Execute the module function
/ * * * * * * / 		modules[moduleId].call(module.exports, module.module.exports, __webpack_require__);
/ * * * * * * /
/ * * * * * * / 		// Flag the module as loaded
/ * * * * * * / 		module.l = true;
/ * * * * * * /
/ * * * * * * / 		// Return the exports of the module
/ * * * * * * / 		return module.exports;
/ * * * * * * / 	}
/ * * * * * * /
/ * * * * * * /
/ * * * * * * / 	// expose the modules object (__webpack_modules__)
/ * * * * * * / 	__webpack_require__.m = modules;
/ * * * * * * /
/ * * * * * * / 	// expose the module cache
/ * * * * * * / 	__webpack_require__.c = installedModules;
/ * * * * * * /
/ * * * * * * / 	// define getter function for harmony exports
/ * * * * * * / 	__webpack_require__.d = function(exports, name, getter) {
/ * * * * * * / 		if(! __webpack_require__.o(exports, name)) {
/ * * * * * * / 			Object.defineProperty(exports, name, {
/ * * * * * * / 				configurable: false./ * * * * * * / 				enumerable: true./ * * * * * * / 				get: getter
/ * * * * * * / 			});
/ * * * * * * / 		}
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// getDefaultExport function for compatibility with non-harmony modules
/ * * * * * * / 	__webpack_require__.n = function(module) {
/ * * * * * * / 		var getter = module && module.__esModule ?
/ * * * * * * / 			function getDefault() { return module['default']; } :
/ * * * * * * / 			function getModuleExports() { return module; };
/ * * * * * * / 		__webpack_require__.d(getter, 'a', getter);
/ * * * * * * / 		return getter;
/ * * * * * * / 	};
/ * * * * * * /
/ * * * * * * / 	// Object.prototype.hasOwnProperty.call
/ * * * * * * / 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/ * * * * * * /
/ * * * * * * / 	// __webpack_public_path__
/ * * * * * * / 	__webpack_require__.p = "";
/ * * * * * * /
/ * * * * * * / 	// Load entry module and return exports
/ * * * * * * / 	return __webpack_require__(__webpack_require__.s = 0);
/ * * * * * * / })
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
/ * * * * * * / ([
/* 0 */
/ * * * / (function(module.exports, __webpack_require__) {

const { sum, mul } = __webpack_require__(1);

console.log(sum(20.30));
console.log(mul(20.30));


/ * * * / }),
/ * 1 * /
/ * * * / (function(module.exports) {

function sum(num1, num2) {
    return num1 + num2;
}

function mul(num1, num2) {
    return num1 * num2;
}

module.exports = {
    sum, mul
}

/ * * * / })
/ * * * * * * / ]);
Copy the code

Webpack configuration

Abbreviate the webpack./ SRC /main.js./dist/bundle.js command to webpack

  1. npm init

  2. Create the webpack.config.js file

    In the command, __dirname refers to the absolute path of the file, entry refers to the entry file of the project, output refers to the export file of the project, path is the path of the export file, filename is the name of the export file, After this configuration, you can use the webpack command instead of webpack. / SRC /main.js./dist/bundle.js

const path = require('path'); Module.exports = {entry: './ SRC /main.js', output: {// path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' } }Copy the code
  1. Use the NPM run build command instead of webpack

    Package. json file is automatically generated after init. Add configuration “build” to package.json file scripts: “Webpack” can then be replaced with the NPM run build command. Using NPM run build gives preference to the local webpack

    {" name ":" meetwebpack ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: no test specified\" && exit 1", "build": "webpack" }, "author": "", "license": "ISC" }Copy the code
  2. Install webPack locally

    NPM install [email protected] - save - dev

The use of the loader

This section describes how to use loader

  • Install the required Loader using NPM
  • Do this under the modules keyword in webpack.config.js

Processing of CSS files

NPM install [email protected] --save-dev NPM install style-loader --save-devCopy the code
module: {
  rules: [{test: /\.css$/.// cs-loader is only responsible for loading CSS files, style-loader is responsible for rendering styles
      use: ['style-loader'.'css-loader']]}}Copy the code

Less file processing

NPM install less [email protected] --save-devCopy the code
{
  test: /\.less$/i,
    loader: [
      // compiles Less to CSS
      'style-loader'.'css-loader'.'less-loader',]}Copy the code

Processing of pictures and other documents

NPM install [email protected] - save - devCopy the code
{
  test: /\.(png|jpg|gif)$/i,
    use: [
      {
        loader: 'url-loader'.options: {
          limit: 8192,},},],}Copy the code

If the image size exceeds the limit, an error message is displayed and file-loader is required

NPM install [email protected] - save - devCopy the code

(dist/ webpack.config.js) : dist/’

const path = require('path');

module.exports = {
  entry: './src/main.js'.output: {
    // Dynamically obtain path
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'.publicPath: 'dist/'
  },
  module: {
    rules: [{test: /\.css$/.// cs-loader is only responsible for loading CSS files, style-loader is responsible for rendering styles
        use: ['style-loader'.'css-loader'] {},test: /\.less$/i,
        loader: [
          // compiles Less to CSS
          'style-loader'.'css-loader'.'less-loader',]}, {test: /\.(png|jpg|gif|jepg)$/,
        use: [
          {
            loader: 'url-loader'.options: {
              limit: 8912,}}]}]}}Copy the code

Image file name processing:

Adding a Name configuration

{
  test: /\.(png|jpg|gif|jepg)$/,
    use: [
      {
        loader: 'url-loader'.options: {
          limit: 8912.name: 'img/[name].[hash:8].[ext]'}}}]Copy the code

ES6 syntax processing loader

NPM install --save-dev [email protected] [email protected] [email protected]Copy the code
{
  test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader'.options: {
            presets: ['es2015']}}}Copy the code

Configure vUE in Webpack

npm install vue --save
Copy the code

Add configuration in webpack.config.js to specify the run-time compiler version (default run-time only version)

resolve: {
  alias: {
    'vue$': 'vue/dist/vue.esm.js'}}Copy the code

When template and EL coexist, the content in template replaces all elements in the DOM mounted by EL with the content in template

Use. Vue files

NPM install [email protected] vue-template-compiler --save-devCopy the code

Note that vue-template-compiler must be the same as vUE

You can omit the. Vue extension and add the Extensions configuration

resolve: {
  extensions: ['.js'.'.css'.'.vue'].alias: {
      'vue$': 'vue/dist/vue.esm.js'}}Copy the code

The use of the plugin

Copyright information plug-in

const webpack = require('webpack');
Copy the code
plugins: [
  new webpack.BannerPlugin(The copyright ultimately belongs to XX.)]Copy the code

HtmlWebpackPlugin

It is not a plug-in that comes with Webpack and needs to be installed manually

NPM install [email protected] - save - devCopy the code
const HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
plugins: [
  new webpack.BannerPlugin(The copyright ultimately belongs to XX.),
  new HtmlWebpackPlugin({
    template: 'index.html'})]Copy the code

Compressed JS plug-in

NPM install [email protected] - save - devCopy the code
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
Copy the code
plugins: [
  new webpack.BannerPlugin(The copyright ultimately belongs to XX.),
  new HtmlWebpackPlugin({
    template: 'index.html'
  }),
  new UglifyjsWebpackPlugin()
]
Copy the code

Setting up a local Server

NPM install [email protected] - save - devCopy the code
devServer: {
  contentBase: './dist'.inline: true // Live monitor
}
Copy the code
// node_modules/.bin/webpack-dev-serverCopy the code

Or you can configure it in package.json

Dev: "webpack-dev-server --open"Copy the code
npm run dev
Copy the code

Separation of webPack configuration files

NPM install [email protected] - save - devCopy the code

base.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
  entry: './src/main.js'.output: {
    // Dynamically obtain path
    path: path.resolve(__dirname, '.. /dist'),
    filename: 'bundle.js'.// publicPath: 'dist/'
  },
  module: {
    rules: [{test: /\.css$/.// cs-loader is only responsible for loading CSS files, style-loader is responsible for rendering styles
        use: ['style-loader'.'css-loader'] {},test: /\.less$/i,
        loader: [
          // compiles Less to CSS
          'style-loader'.'css-loader'.'less-loader',]}, {test: /\.(png|jpg|gif|jepg)$/,
        use: [
          {
            loader: 'url-loader'.options: {
              limit: 8912.name: 'img/[name].[hash:8].[ext]'}}]}, {test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader'.options: {
            presets: ['es2015'}}}, {test: /\.vue$/,
        use: ['vue-loader']]}},resolve: {
    extensions: ['.js'.'.css'.'.vue'].alias: {
      'vue$': 'vue/dist/vue.esm.js'}},plugins: [
    new webpack.BannerPlugin(The copyright ultimately belongs to XX.),
    new HtmlWebpackPlugin({
      template: 'index.html'
    }),
    // new UglifyjsWebpackPlugin()].// devServer: {
  // contentBase: './dist',
  // Inline: true // Real-time listening
  // }
}
Copy the code

prod.config.js

const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
const webpackMerge = require('webpack-merge');
const baseConfig = require('./base.config');

module.exports = webpackMerge(baseConfig, {
  plugins: [
    new UglifyjsWebpackPlugin()
  ]
})
Copy the code

dev.config.js

const webpackMerge = require('webpack-merge');
const baseConfig = require('./base.config');

module.exports = webpackMerge(baseConfig, {
  devServer: {
    contentBase: './dist'.inline: true // Live monitor}})Copy the code

Package.json

The build and dev paths are configured using –config

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config ./build/prod.config.js"."dev": "webpack-dev-server --open --config ./build/dev.config.js"
},
Copy the code