webpack大全---------(基础配置篇)----4.webpack实例三

上一篇:webpack大全---------(基础配置篇)----2.webpack实例二

webpack实例三:讲述代码效验模块eslint、引入第三方模块的处理、图片的打包处理。

第一步:安装配置。

     yarn add webpack webpack-cli -D
     yarn add webpack-dev-server  -D   //安装热服务,后面会讲解
     yarn add style-loader css-loader less-loader  less  -D //处理css less需要的loader
     yarn add html-webpack-plugin  -D  //打包生成html文件需要的第三方插件。
     yarn add mini-css-extract-plugin  -D //进行css代码抽离需要的插件,内置有loader 。
     yarn add optimize-css-assets-webpack-plugin -D  //进行css代码的压缩优化
     yarn  add uglifyjs-webpack-plugin  -D  //进行css代码的优化和压缩的时候会,就是在production模式下也会接触js代码的压缩,采用此插件可以阻止此发生。
     yarn add html-withimg-loader  -D 处理html文件的使用img标签引入图片的压缩图片的模块。
     yarn add file-loader  -D 处理图片的loader (无参数)
     yarn add url-loader -D 处理图片的loader  (有参数版)
     yarn add  eslint  -D代码效验的核心模块
     yarn add eslint-loader  -D代码效验的loader 依赖于eslint
     yarn add babel-loader @babel/core @babel/preset-env  -D //用来解析js语法。
     yarn add @babel/polyfill  -D //解析一些新的es7特性的要,需要在使用该特性的js文件下引用。
     yarn add  expose-loader -D  //安装强制暴露模块,强制暴露第三方模块用。

并且创建一个根目录下创建一个src目录,在里面创建几个文件:index.html、index.css、index.js、
、.eslintrc.json、a.js.(到eslint官网去下载需要效验的配置json包)
并且在根目录下创建webpack.config.js配置文件:
pack.json文件中写入如下内容:

     "scripts": {
      "build": "webpack --config webpack.config.js",      //表示默认的情况下 npm run build则启动这个命令。
      "dev": "webpack-dev-server"         //启动热服务的时候 npm run dev
    }, 

第二步1:写入内容(校验代码部分)。

a.js

 require('@babel/polyfill');   //需要引入这个包
 class B{

 }
function *gen(params){
   yield  1;
}
console.log(gen().next());

'aaa'.includes('a');      //要用@babel/polyfill 这个包用来转换这个语法

index.js

  const fn = ()=>{
   console.log("我是fn")
};
fn();

//@log属于类的装饰器
@log
class A{  //相当于在A这个类里面加入一个实例属性 a =1  ES7的语法
   a = 1;
}
let a = new A();
console.log(a.a);

function log(A) {
   console.log(A)
}

webpack.config.js

let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let MiniCSSExtractPlugin = require('mini-css-extract-plugin');
let webpack = require('webpack');

module.exports = {
    devServer: {
        port:3000,
        progress:true,
        contentBase:'./dist' ,
        compress:true,
    },
    mode: "development",
    entry:'./src/index.js',
    output:{
        filename: "bundle.js",
        path: path.resolve(__dirname,'dist'),
        //publicPath: "https://www.justyunmeng.com"  给所有的打包后的src加上这个访问前缀
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html',
        }),
    ],
    
    module: { //模块
        rules: [
             {//校验js语法 用eslint包       //需要安装eslint 和 eslint-loader
                  test:/\.js/,
                  use:{
                      loader: "eslint-loader",
                      options:{
                          enforce:'pre'   //因为loader是从下到上执行 从右到左执行的  使用pre可以强制先执行这个文件 post表示最后执行
                      }
                  }
            },

            //转换js语法
            {
                test:/\.js$/,     // 安装的时候需要安装 babel-loader  @babel/core  @babel/preset-env
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ["@babel/preset-env"],        //es6->es5
                        plugins:[   //加入babel的插件
                            ["@babel/plugin-proposal-decorators", { "legacy": true }],         //当类使用修饰器的时候使用
                            ["@babel/plugin-proposal-class-properties", { "loose" : true }],  //当使用类的时候
                            "@babel/plugin-transform-runtime"                                 //进行generate语法的转换
                        ]
                        //当使用一些es7的函数的时候要在相对应的js文件引入 require(@babel/polyfill)
                    }
                },
                include:path.resolve(__dirname,'src'),
                exclude:/node_module/
            },

            {
                test:/\.css$/,
                use:[
                    MinCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            },
            {
                test:/\.less$/,
                use:[
                    MinCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'less-loader'
                ]
            }
        ]
    }
};

效验成功截图:
在这里插入图片描述

第二部:写入内容(引入第三方模块处理部分和图片处理)

文件:index.css、index.js、index.html、webpack.config.js、图片Remix.jpg.

index.js

   jquery(外部模块)的引入方法/

import  $ from 'jquery'; //window对象拿不到$;
//三种解决方法
//1)
import $ from 'expose-loader?$!jquery';    //这种方法可以直接子拿到

//2)   //将expose-loader写到webpack配置文件中
import $ from 'jquery';
console.log(window.$);

//3) //如何需要在每个模块中注入$符号 使用webpack分配的插件,不需要配置expose-loader
import  $ from 'jquery';
console.log($);

//4) 外部引用了cdn模块情况下,又想这里写下引用$符号,但是打包的时候会把引用的又打包,需要在webpack配置文件中忽略掉。
import $ from 'jquery';   //写在这里为心里安慰
console.log($);   //直接可以拿到这个$,因为外部引用了cdn

//JS中图片的处理//
//webpack中打包我们的图片
//1)在js中创建图片来引入
//file-loader默认会在内部生成一张图片到build目录下
//把生成的图片的名字返回回来

import './index.less';
import  './index.css';
import remix from './Remix.jpg';
console.log(remix);
let image = new Image();
image.src = remix;
document.body.appendChild(image);

//2)css中进行引入背景图片(css-loader的作用)


//3)直接html进行背景图片的引入(使用到html-withimg-plugin模块);

index.css

	body{
	    background-color: red;
	}
	 #div1{
	    width: 500px;
	    height: 500px;
	    background-image:url("./Remix.jpg");
	    background-size: 100% 100%;
	    -moz-background-size: 100% 100%;
	}
	#div1 img{
	    width: 500px;
	    height: 500px;
	}
	
	img{
	    width: 200px;
	    height: 200px;
	}

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<style>
    body{  /*优先级比less和css的高*/
       background-color: yellow;
    }
</style>
<body>
	<div id="div1">
	</div>
<img src="./Remix.jpg" alt="" style="width: 100px;height: 100px"/>	
</body>
</html>

webpack.config.js

    let path = require('path');
	let HtmlWebpackPlugin = require('html-webpack-plugin');
	let MinCssExtractPlugin = require('mini-css-extract-plugin');
	let OptimizeCss = require('optimize-css-assets-webpack-plugin');
	let UglifyJsPlugin = require('uglifyjs-webpack-plugin');
	let webpack = require('webpack');

module.exports = {
    devServer: {
        port:3000,
        progress:true,
        contentBase:'./dist' ,
        compress:true,
    },
    optimization: {
        minimizer: [
            new  UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true
            }),
            new OptimizeCss()
        ]
    },
    mode: "development",
    entry:'./src/index.js',
    output:{
        filename: "bundle.js",
        path: path.resolve(__dirname,'dist'),
        //publicPath: "https://www.justyunmeng.com"  给所有的打包后的src加上这个访问前缀
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html',
        }),
        new MinCssExtractPlugin({
            filename:'css/main.css'
        }),
        /* new webpack.ProvidePlugin({     //在每个模块中注入jquery
             $:'jquery'
         })*/
    ],

    //忽略打包
    externals: {
        jquery:'$'
    },

    module: { //模块
        rules: [
            //当使用第三方外部的包的时候
            /*{
                test:require.resolve('jquery'),
                use:'expose-loader?$'
            },*/

            {
                test:/\.html$/,       //当加载html页面的图片的时候使用这个loader进行图片的压缩
                use:'html-withimg-loader'
            },

            //处理图片的url-loader
            {
                test:/\.(png|jpg|gif)$/,   //校验的图片的类型
                //use:"file-loader",    //也可以用这个,但是url-loader可以穿参数
                use:{
                    loader: "url-loader",     //用这个可以设置一些东西
                    options:{
                        limit:1,              //限制不进行base64的转换  如果要超过200k就行了转换成base64的话 可以这么写 limit:200*1024
                        outputPath:'img/',    //产出的路径(打包后的文件夹)
                        //publicPath:'https://justyunmeng.com/'  //只给图片的加上这个前缀
                    }
                }
            },

            //转换js语法
            {
                test:/\.js$/,     // 安装的时候需要安装 babel-loader  @babel/core  @babel/preset-env
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ["@babel/preset-env"],        //es6->es5
                        plugins:[   //加入babel的插件
                            ["@babel/plugin-proposal-decorators", { "legacy": true }],         //当类使用修饰器的时候使用
                            ["@babel/plugin-proposal-class-properties", { "loose" : true }],  //当使用类的时候
                            "@babel/plugin-transform-runtime"                                 //进行generate语法的转换
                        ]
                        //当使用一些es7的函数的时候要在相对应的js文件引入 require(@babel/polyfill)
                    }
                },
                include:path.resolve(__dirname,'src'),
                exclude:/node_module/
            },

            {
                test:/\.css$/,
                use:[
                    MinCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            },
            {
                test:/\.less$/,
                use:[
                    MinCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'less-loader'
                ]
            }
        ]
    }
};

效果图:
打包成功:在这里插入图片描述
浏览器预览:

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值