• Webpack基本插件


    webpack基本打包插件使用

    webpack 初始化

    1. 安装webpack
    npm i webpack webpack-cli -D
    
    1. 安装webpack开发服务器插件
    npm i webpack-dev-server -D
    
    1. 设置自定义config文件和npm运行命令
    // package.json
    {tr
      "name": "webpack4_s",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "build": "webpack --config webpack.my.config.js",
        "dev": "webpack-dev-server --config webpack.my.config.js"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "webpack": "^4.43.0",
        "webpack-cli": "^3.3.11",
        "webpack-dev-server": "^3.10.3"
      }
    }
    
    1. 配置 mode entry output devServer
    /* ------------webpack.my.config.js------------ */
    const path = require('path');
    /* 导出配置 */
    module.exports = {
        mode: 'development',//模式
        entry: './src/index.js',//入口
        output: {//出口
            //打包文件名 中间八位随机生成 bundle.7f921d2c.js
            filename: 'bundle.[hash:8].js',
            //打包出口的绝对路径
            path: path.resolve('./build')
        },
        devServer: {
            contentBase: './build',//服务器根路径
            port: 8888,//端口
            compress: true,//开启gzip压缩
            hot: true,//热更新,文件改变保存会触发编译
        }
    }
    

    实现html文件打包

    安装相关插件

     npm i html-webpack-plugin   clean-webpack-plugin   html-withimg-loader -D
    

    1.引入方式

    /* 删除build目录旧文件 */
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    /* 打包html */
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    

    2.作为plugin使用

    plugins: [
        // 删除旧文件
        new CleanWebpackPlugin(),
        //打包html
        new HtmlWebpackPlugin({
            title: '首页',//通过ejs模板可以渲染到html
            filename: 'index.html',//打包生产文件名
            template: './src/index.html',//打包html模板
            hash: true,//js引入加入hash  bundle.7f921d2c.js?23de33ee2323
        })
    ]
    

    3.效果

    <!-- 打包模板 -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
        <div id="app">666</div>
    </body>
    </html>
    <!-- 生成html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>首页</title>
    </head>
    <body>
        <div id="app">666</div>
        <script src="bundle.c4e05e95.js?c4e05e9530cf5a369b9d"></script>
    </body>
    </html>
    

    Css,Less文件处理

    1.编译打包css,less到js
    安装插件

    npm i style-loader css-loader less less-loader -D
    
    

    配置

    module: {
        /* rules里面内容执行顺序从下往上,从右向左 */
        rules: [
            {
                test: /.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            }, {
                test: /.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader'
                ]
            }
        ]
    }
    

    引入css/less进行打包的方式

    /* ---------index.js--------- */
    //引入css和less
    import './index.css';
    import './index.less';
    

    2.打包成css文件到指定目录
    安装插件

    npm i mini-css-extract-plugin -D
    

    引入方式

    /* 打包到css/目录 */
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    

    使用方式

    rules中将所有'style-loader'替换为MiniCssExtractPlugin.loader
    
    plugins加入一条 new MiniCssExtractPlugin({ filename: 'css/bundle.css' })
    

    3.给transform等样式类型加入前缀
    安装插件

    npm i postcss-loader autoprefixer -D
    

    使用方式

    /* ---------webpack.my.config.js--------- */
    rules: [
        {
            test: /.css$/,
            use: [
                // 'style-loader',
                MiniCssExtractPlugin.loader,
                'css-loader',
                {
                    loader: 'postcss-loader',//加载插件
                    options: {
                        plugins: [require('autoprefixer')]//引用加前缀插件
                    }
                }
            ]
        }, {
            test: /.less$/,
            use: [
                // 'style-loader',
                MiniCssExtractPlugin.loader,
                'css-loader',
                'less-loader',
                {
                    loader: 'postcss-loader',
                    options: {
                        plugins: [require('autoprefixer')]
                    }
                }
            ]
        }
    ]
    /* -------------package.json------------- */
    // 标识浏览器
    "browserslist": [
        "defaults",
        "not ie <= 8",
        "last 2 versions",
        "> 1%",
        "iOS >= 7",
        "Android >= 4.0"
    ]
    

    效果

    /* index.css */
    #app{
        border:2px solid mediumseagreen;
        transform: rotate(-5deg);
    }
    /* index.less */
    body{
        background-color: wheat;
        #app{
            font-size: 50px;
            color:green;
        }
    }
    
    /* 生成的bundle.css */
    #app{
        border:2px solid mediumseagreen;
        -webkit-transform: rotate(-5deg);
                transform: rotate(-5deg);
    }
    body {
      background-color: wheat;
    }
    body #app {
      font-size: 50px;
      color: green;
    }
    

    4.优化
    实现生产环境css压缩打包

    const TerserJSPlugin = require('terser-webpack-plugin');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
    module.exports = {
      optimization: {
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
      },
      plugins: [
        new MiniCssExtractPlugin({
          filename: '[name].css',
          chunkFilename: '[id].css',
        }),
      ],
      module: {
        rules: [
          {
            test: /.css$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader'],
          },
        ],
      },
    };
    

    js文件打包

    1.ES6语法转换为ES5

    npm i babel-loader @babel/core @babel/preset-env -D
    

    使用方式

    //添加的rule
    {
        test: /.js$/,
        exclude: /node_modules/,
        use: [{
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env']
            }
        }]
    }
    

    输出文件对比

    使用插件前
    let fn = (str) => {
        console.log(str);
    }
    使用插件后
    var fn = function fn(str) {
      console.log(str);
    };
    

    2.增加对class和装饰类的支持以及补充低版本浏览器缺少的api

    @babel/plugin-proposal-decorators
    @babel/plugin-proposal-class-properties  
    @babel/plugin-transform-runtime
    @babel/runtime --save 上线需要的补丁
    @babel/polyfill --save 直接require引入的包
    

    使用方式

    //修改之前的rule为:
    {
        test: /.js$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, 'src'),
        use: [{
            loader: 'babel-loader',
            options: {
                presets: [
                    '@babel/preset-env',
                ],
                plugins: [
                    ['@babel/plugin-proposal-decorators', { 'legacy': true }],//装饰类
                    ['@babel/plugin-proposal-class-properties', { 'loose': true }],//类
                    '@babel/plugin-transform-runtime'
                ]
            }
        }]
    }
    

    效果

    /* ----------index.js---------- */
    // 使用类和装饰类
    @log
    class A {
        a = 1;
    }
    let a = new A();
    console.log(a.a);
    function log(target) {
        console.log(target);
    }
    
    /* 打包后的文件 */
    var A = log(_class = (_temp = function A() {
      _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, A);
    
      this.a = 1;
    }, _temp)) || _class;
    
    var a = new A();
    console.log(a.a);
    
    function log(target) {
      console.log(target);
    }
    

    多页面自定义打包

    module.exports = {
        mode: 'development',
        entry: {
            a: './src/a.js',
            b: './src/b.js'
        },
        output: {
            filename: '[name].[hash:8].js',
            path: path.resolve('./build')
        },
        plugins: [
            /* 自定义输出html */
            new HtmlWebpackPlugin({
                title: 'a',
                filename: 'a.html',/* 输出文件名 */
                template: './src/index.html',
                chunks: ['a']/* 需要导入的js */
            }),
            new HtmlWebpackPlugin({
                title: 'b',
                filename: 'b.html',
                template: './src/index.html',
                chunks: ['b']
            })
        ]
    }
    

    图片引入

    文件引入 使用url-loader,file-loader处理
    html图片路径处理 html-withimg-loader处理
    使用方式:增加两个rule

    {
        test: /.(jpg|png|gif|)$/,
        use: [{
            loader: 'url-loader',
            options: {
                limit: 200*1024,//小于200k用base64转化
                outputPath: 'images/',
                esModule: false,/* 解决图片路径为default */
                // publicPath: "http://www.xxx.com"/* 设置图片域名 */
            }
        }]
    }, {
        test: /.html$/,
        use: 'html-withimg-loader'
    }
    

    效果

    /* index.js */
    import imgFile from './1.jpg';
    let img = new Image(200, 300);
    img.src = imgFile;
    document.body.appendChild(img);
    /* index.html */
    <div id="app">666</div>
    <img src="./1.jpg" alt="直接写在html的图片">
    
    
    /* 打包结果 */
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><%= htmlWebpackPlugin.options.title %></title>
        <link href="css/bundle.css?35d8506e121620c96075" rel="stylesheet"></head>
    <body>
        <div id="app">666</div>
        <img src="images/3667f5d46b7893c97ec4dc0f6223c803.jpg" alt="直接写在html的图片">
        <script src="bundle.35d8506e.js?35d8506e121620c96075"></script></body>
    </html>
    
    
    
  • 相关阅读:
    用addOnGlobalLayoutListener获取View的宽高
    用addOnGlobalLayoutListener获取View的宽高
    用addOnGlobalLayoutListener获取View的宽高
    ElasticSearch封装查询、多条件查询、模糊查询工具类
    java操作ElasticSearch(es)进行增删查改操作
    如何构建尽可能小的容器镜像?
    perl 合并日志处理+并发管理器
    NoSQL还是SQL?这一篇讲清楚
    perl 跨行匹配 /s
    perl 改变换行符 合并日志
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/12990193.html
Copyright © 2020-2023  润新知