美文网首页
表严肃webpack精讲

表严肃webpack精讲

作者: 雨y飘零久 | 来源:发表于2019-05-24 08:03 被阅读0次

    安装配置

    • 安装webpack
    npm init -y  # npm初始化,生成package.json文件
    npm i webpack webpack-cli -D  #安装webpack和webpack-cli
    

    package.json

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "pack": "node_modules\\.bin\\webpack --watch" #windows的斜线写法  --watch监听是否有文件修改
      },
    
    • demo
    1. 整体demo布局


      image.png
    2. 编写文件信息
      js/a.js

    var msg = require('./b').msg;
    console.log("msg:", msg);
    

    js/b.js

    var msg = "Yo.";
    module.exports = {msg : msg};
    

    index.html

    <body>
    
    <script src="js/pack.js"></script>
    </body>
    

    webpack.config.js

    module.exports = {
        entry: ".\\js\\a",
        output: {
            filename: 'pack.js',
            path: __dirname + "\\js"
        }
    }
    
    1. 运行
    npm run pack # webpakc生成pack.js文件
    

    entry和output

    安装同安装webpack

    1. 整体demo布局


      image.png
    2. 编写文件信息
      js/base.js

    var open = false;
    
    export{open};
    

    js/home.js

    import open from './base'
    
    if(open){
        document.body.innerHTML = 
        `<a href="./signup.html">注册</a>`
    }
    

    js/signup.js

    import open from './base'
    
    if(open){
        document.body.innerHTML = 
            `<h1>欢迎注册</h1>`
    }else{
        document.body.innerHTML = 
            `<h1>没有权限注册</h1>`        
    }
    

    page/index.html

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

    page/signup.html

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

    webpack.config.js

    module.exports = {
        entry:{
            home: "./js/home.js",
            signup: "./js/signup.js"
        },
        output:{
            filename: "[name].bundle.js",
            path: __dirname + "\\dist"
        }
    }
    
    1. 运行
    npm run pack # 自动生成dist目录下的home.bunlde.js和signup.bundle.js
    

    leader

    安装同安装webpack

    1. 整体demo布局


      image.png
    2. 编写文件信息
      js/base.js

    var debug = true;
    
    export{debug}
    

    js/index.js

    import debug from "./base";
    import "../css/base.css";
    import "../css/base2.css"
    
    console.log('debug:' ,debug);
    

    index.html

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

    css/base.css

    body{
        background: #ccc;
    }
    

    css/base2.css

    body{
        background: #000;
    }
    

    webpack.config.js

    module.exports = {
        entry: "./js/index.js",
        output:{
            filename: "bundle.js",
            path: __dirname + "\\dist",
        },
        module: {
            rules:[
                {
                    test: /\.css$/,
                    //***use从右往左开始***
                    use:['style-loader' ,'css-loader']
                }
                
            ]
        }
    
    }
    
    1. 安装css-loader和style-loader
    npm i css-loader style-loader -D
    
    1. 运行
    npm run pack # 自动生成dist目录下的bundle.js
    

    动态加载样式

    安装同安装webpack

    1. 整体demo布局


      image.png

    2.编写文件内容
    index.js

    import "./index.css";
    import "./index2.css";
    console.log("Yo.!!!");
    

    index.html

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

    index.css

    
    
    
    body {
        background: royalblue;
    }
    

    index2.css

    body {
        border: 2em solid;
    }
    

    webpack.config.js

    module.exports = {
        mode: "development",
        entry: "./index.js",
        output:{
            filename: "bundle.js",
            path: __dirname + "\\dist",
        },
        module:{
            rules: [
                {
                    test: /\.css$/i,
                    //***从下往上开始的***/
                    use: [
                        {
                            loader: "style-loader/url", // 将<link>插入到<head>中
                        },
                        {
                            loader: "file-loader", // 加载文件且生成文件地址
                            options: {
                                publicPath: './dist', // 公共目录,即地址栏中的目录地址
                                name: '[name].bundle.css', // 文件名
                            },
                        },
                    ],
                },
            ],
        },
    }
    
    1. 安装file-loader、css-loader和style-loader
    npm i file-loader css-loader style-loader -D 
    
    1. 运行
    npx webpack -w    //自动生成dist目录下的bundle.js、index.bundle.css和index2.bundle.css
    

    动态加载文件

    • 加载文件地址
      安装同安装webpack
    1. 整体demo布局


      image.png
    2. 编写文件内容
      index.js
    import './index.css';
    import src from "./img/chong.jpg";
    
    let  img = document.createElement('img');
    img.src = src;
    document.body.appendChild(img);
    

    index.html

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

    index.css

    body {
        background: url("./img/xiu.gif");
    }
    
    img {
        max-width: 20em;
    }
    

    webpack.config.js

    module.exports = {
      mode   : 'development',
      entry  : './index.js',
      output : {
        filename   : 'bundle.js',
        path       : __dirname + '/dist',
        publicPath : './dist/', // 公开文件相对index.html的地址
      },
      module : {
        rules : [
          // CSS loader
          {
            // 以.css结尾的文件
            test : /\.css$/i,
            use  : [ 'style-loader', 'css-loader' ],
          },
          // 图片 loader
          {
            // 以.jpg、.jpeg、.png或.gif结尾的文件
            test : /\.(jpg|jpeg|png|gif)$/i,
            use  : [
              {
                loader : 'file-loader',
              },
            ],
          },
        ],
      },
    };
    
    1. 安装file-loader、css-loader和style-loader
    npm i file-loader css-loader style-loader -D 
    
    1. 运行
    npx webpack -w    //自动生成dist目录下的bundle.js、xxx.gif和xxx.jpg
    
    • 直接转换图片数据
    1. 整体demo布局


      image.png
    2. 编写文件内容
      index.js

    import  c from "./img/chong.jpg";
    import  g from "./img/gua.jpg";
    import  l from "./img/lian.jpg";
    import  x from "./img/xiu.gif";
    
    let container = document.querySelector('.container');
    let body      = document.body;
    
    function append (src, parent) {
      let img = document.createElement('img');
      img.src = src;
      parent.appendChild(img);
    }
    
    append(c, container);
    append(g, container);
    append(l, container);
    append(x, body);
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
          .container {
            font-size: 0;
          }
        
          img {
            width: 33.3333333%
          }
        </style>
    </head>
    <body>
      
    <div class="container"></div>
    
    <script src="dist/bundle.js"></script>
    </body>
    </html>
    

    webpack.config.js

    module.exports = {
      mode   : 'development',
      entry  : './index.js',
      output : {
        filename   : 'bundle.js',
        path       : __dirname + '/dist',
        publicPath : './dist/',
      },
      module : {
        rules : [
          {
            test : /\.(jpg|png|jpeg|gif)/i,
            use  : [
              {
                loader  : 'url-loader',
                options : {
                  limit : 60 * 1024, // byte
                },
              },
            ],
          },
        ],
      },
    };
    
    1. 安装file-loader和url-loader
    npm i file-loader url-loader -D
    
    1. 运行
    npx webpack -w  //自动生成dist目录下的bundle.js、xxx.gif
    

    加载数据(json、csv)

    安装同安装webpack

    1. 整体demo布局


      image.png
    2. 编写文件内容
    • json
      nav.json
    [
        {
          "text": "yo",
          "url": "#yo"
        },
        {
          "text": "ha",
          "url": "#ha"
        },
        {
          "text": "la",
          "url": "#la"
        },
        {
          "text": "muhaha",
          "url": "#muhaha"
        }
      ]
    

    index.js

    import list from './nav';
    // import list from './nav.csv';
    
    const nav = document.querySelector('nav');
    
    list.forEach(it => {
      if (!it.text)
      return;
    
      let a       = document.createElement('a');
      a.innerText = it.text;
      a.href      = it.url;
    
      nav.appendChild(a);
    });
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
    <nav></nav>
    <script src="./dist/bundle.js"></script>
    </body>
    </html>
    

    index.css

    /* attention */
    :root {
        font-family: sans-serif;
    }
    /* attention */
    
    /* attention */
    nav > * {
        display: inline-block;
        padding: .5em;
    }
    /* attention */
    
    • csv
      打开index.js第2行注释,注释第一行
      nav.csv
    text, url
    yo, #yo
    ha, #ha
    la, #la
    muhaha, #muhaha
    

    webpack.config.js

    module.exports = {
        mode: "development",
        entry: "./index.js",
        output:{
            filename: "bundle.js",
            path: __dirname + "\\dist",
        },
        module: {
            rules: [
                {
                    test:/\.csv$/i,
                    use:  [
                        {
                            loader: "csv-loader",
                            options: {
                                header: true,
                            }
                        }
                    ]
                }
            ]
        }
    }
    
    1. (若加载csv)安装csv-loader和papaparse
    npm i csv-loader papaparse -D
    
    1. 运行
    npx webpack -w
    

    将HTML纳入打包范围

    安装同安装webpack

    1. 整体demo布局


      image.png
    2. 编写文件内容

    index.js

    console.log("1");
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <h1>Yo.</h1>
        <input type="text" disabled>
    </body>
    </html>
    

    webpack.config.js

    
    const Clean = require('clean-webpack-plugin');
    const Html = require('html-webpack-plugin');
    
    module.exports = {
        mode: "development",
        entry: "./index.js",
        output:{
            filename: "bundle.[hash].js",
            path: __dirname + "\\dist",
        },
        plugins: [
            new Clean(), //清除dist目录
            new Html({
                template: './index.html',    //模板文件
                filename: 'index.html',    //修改模板文件打包名称
                minify: {
                    collapseBooleanAttributes : true,   //清除boolen值为默认简写
                    collapseWhitespace        : true,   //清除空格
                    removeComments            : true,   //清除注释
                }
            })
        ]
    }
    
    1. 安装插件clean-webpack-plugin和html-webpack-plugin
    npm i clean-webpack-plugin html-webpack-plugin -D
    

    4.运行

    npx webpack -w
    

    懒癌的福音

    安装同安装webpack

    1. 整体demo布局


      image.png
    2. 编写文件内容

    index.html

    <h1>Yooooooo.</h1>
    

    webpack.config.js

    const Html = require('html-webpack-plugin');
    
    module.exports = {
        mode: "development",
        entry: "./index.js",
        output:{
            filename: "bundle.js",
            path: __dirname + "\\dist",
        },
        plugins: [
            new Html({
                template: './tpl.html',
            })
        ]
    }
    

    package.json

      "scripts": {
        "start": "npx webpack-dev-server --open"
      },
    
    1. 安装html-webpack-plugin和webpack-dev-server
    npm i html-webpack-plugin webpack-dev-server -D
    
    1. 运行
    npm run start   //package.json设置了快捷命令
    

    不同模式不同配置

    1.整体demo布局


    image.png

    node_modules文件夹太大,因此删去,直接npm i
    package.json

    {
      "name": "webpackdemo3",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "npx webpack-dev-server --open --config webpack.dev.js",
        "build": "npx webpack --config webpack.prod.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "clean-webpack-plugin": "^2.0.2",
        "html-webpack-plugin": "^3.2.0",
        "webpack": "^4.32.2",
        "webpack-cli": "^3.3.2",
        "webpack-dev-server": "^3.4.1",
        "webpack-merge": "^4.2.1"
      }
    }
    
    1. 编写文件内容

    index.html

    <h1>Yo.</h1>
    

    webpack.common.js

    const Html = require('html-webpack-plugin');
    
    module.exports = {
      entry  : './index.js',
      output : {
        filename : 'bundle.js',
        path     : __dirname + '/dist',
      },
    };
    

    webpack.dev.js

    const Html  = require('html-webpack-plugin');
    const merge = require('webpack-merge');
    
    module.exports = merge(require('./webpack.common'), {
      mode    : 'development',
      devtool : 'inline-source-map',
      plugins : [
        new Html({
          template : './tpl.html',
        }),
      ],
    });
    

    webpack.prod.js

    const Clean = require('clean-webpack-plugin');
    const Html  = require('html-webpack-plugin');
    const merge = require('webpack-merge');
    
    module.exports = merge(require('./webpack.common'),
      {
        mode    : 'production',
        plugins : [
          new Clean(),
          new Html({
            template : './tpl.html',
            minify   : {
              collapseWhitespace : true,
              removeComments     : true,
            },
          }),
        ],
      });
    
    1. 运行

    开发模式

    npm start    //package.json设置了快捷命令
    

    生产模式

    npm run build //package.json设置了快捷命令
    

    相关文章

      网友评论

          本文标题:表严肃webpack精讲

          本文链接:https://www.haomeiwen.com/subject/zmcwzqtx.html