webpack学习笔记(webpack最通俗易懂的入门课程笔记,持续更新中)

目录

【P1】webpack简介

【P2】entry与output

2.1 一个小栗子

 2.2 小栗子的解释

2.2.1 entry

2.2.2 output

【P3】plugin

3.1 html-webpack-plugin 

3.2 clean-webpack-plugin

【P4】devServer与mode

4.1 devServer

 4.2 mode


之前是看书学的webpack,但感觉还是不太容易入门,先看视频学一下了解webpack,有点基础再看书,

学习资料:webpack最通俗易懂的入门课程_哔哩哔哩_bilibili

【P1】webpack简介

在根目录下,先使用npm init指令创建package.json文件,然后使用npm i -D webpack webpack-cli,npm i -g webpack webpack-cli安装,之后就可以使用了,但是我在安装的过程中踩了个坑,踩坑的解决办法更新在另一个博客了:

webpack -v报错:Cannot find module ‘webpack-cli/package.json‘__Kayo_的博客-CSDN博客

【P2】entry与output

2.1 一个小栗子

先按照视频的流程写一个小栗子:

show.js

show函数传入一个参数content,并且获取id为box的节点,把这个节点里的内容赋值成content

const show = content => {
    const box = document.getElementById('box')
    box.innerHTML=`hello ${content}`
}

export { show }

mian.js

执行show函数

import { show } from './show.js'

show('kayokayokayo')

webpack.config.js

const path = require('path')

module.exports = {
    entry:'./src/main.js',
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'bundle.js'
    }
}

执行webpack指令进行打包,打包好之后,根目录下多了一个dist文件,dist文件中多了一个bundle.js文件,然后在index.html中引入打包好的文件:

index.html

在Body中写一个id为box的节点,并且引入打包好的bundle.js文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box"></div>
    <script src="dist/bundle.js">

    </script>
</body>
</html>

打开index.html,效果:

 2.2 小栗子的解释

以上是一个简单的webpack栗子,其实webpack是基于webpack.config.js执行的,当在控制台输入webpack时,webpack会去寻找webpack.config.js文件,找到这个文件之后,就会进入到文件中去查看参数,

2.2.1 entry

入口参数。

规定了打包的入口,入口可以是一个文件,也可以是多个文件。

单入口:入口文件只有一个,可以使用字符串表示

entry:'./src/main.js'

多入口打包成一个文件:入口文件有多个,并且打包成一个文件,可以使用数组表示

一个小栗子:

entry:['./src/1.js', './src/2.js'],

1.js:

console.log('第一个入口文件')

2.js:

console.log('第二个入口文件')

重新打包,打开index.html,看到页面显示为空,但是控制台输出:

在打包之后,会把他们合在一起,最后打包在一个文件中。当然,也可以把多入口打包成多个文件。

多入口打包成多个文件:多入口文件,并且打包成多个文件,用对象表示

entry用key:value的形式表示,value指定了入口文件的路径,key给对应的文件指定了一个name,

在output的filename中,用[name]获取到key,根据不同的key把结果输出到不同的文件中。

[name] :获取到入口文件的key

[id]:获取到入口文件的index

const path = require('path')

module.exports = {
    entry:{
        one:'./src/1.js', //用key:value的形式给入口文件做了命名,value是文件,key是名字
        two:'./src/2.js'
    },
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'[name].bundle.js' //[name]打包时会去找key值
    }
}

再次webpack,dist下会多出两个文件:

2.2.2 output

出口参数。

出口参数中有两个值是必须的,path和filename,path规定了打包文件的输出路径,filename规定了输出的打包文件的命名。

path: path.resolve(__dirname, 'dist')

__dirname: 获取当前文件夹的绝对路径,可以参考node中的__dirname_weixin_30810583的博客-CSDN博客

这里列出的只是很少的参数,只是一点点入门,其他参数可以查找webpack的官方文档

【webpack.config.js的名字可以改变吗?】是可以的,但是在运行的时候也需要更改,改成webpack --config 名字 ,就可以了

【P3】plugin

plugin插件,插件可以帮助构建过程中的一些流程,提高效率,插件有官方的,也有第三方的,插件放在plugins参数中,值是一个数组。webpack的插件非常多,这里只介绍常用的两个插件。

3.1 html-webpack-plugin 

用于生成页面。他会生成一个html,在html文件中自动填写打包的js。

安装:使用npm i html-webpack-plugin -D安装。

使用:具体的方法可以在github中查找插件名称使用。

参数:

title : 使用<%= htmlWebpackPlugin.options.title%>可以规定这个值的填写位置。

template:模板文件,数值是一个地址,规定了生成html的模板。在生成html文件时,会先找到模板,通过模板来生成html。

filename: 配置生成文件的名字。

inject:配置生成文件中,script标签引入的位置,比如设置inject:'head',引入的script标签就会在head标签里。值为true、body的时候,会把js放在body的结束标签前。inject默认值为true。

hash:会在js文件后面加上hash值。

chunks:webpack打包生成的文件是chunks,每一个文件就叫一个chunk,chunks可以规定打包的文件列表。比如设置chunks:['one'],就会只加载key为one的文件。

minify:是否对生成的文件进行压缩(删除)。具体方式可以参考文档,比如collapseWhitespace,表示是否压缩空格、removeAttributeQuotes,是否压缩引号、removeComments,是否压缩注释。

小栗子:

引入

const HtmlWebpackPlugin = require('html-webpack-plugin')

使用

    plugins:[
        new HtmlWebpackPlugin({
            title:"kayo",
            template:'./test.html',
            filename:'index.html',
            inject: true,
            hash: true,
            chunks:['one'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        })
    ]

生成多个文件:

    plugins:[
        new HtmlWebpackPlugin({
            title:"kayo",
            template:'./test.html',
            filename:'index.html',
            inject: true,
            hash: true,
            chunks:['one'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        }),
        new HtmlWebpackPlugin({
            title:"kayo2",
            template:'./test.html',
            filename:'index2.html',
            inject: true,
            hash: true,
            chunks:['two'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        })
    ]

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= htmlWebpackPlugin.options.title%></title>
</head>
<body>
    
</body>
</html>

3.2 clean-webpack-plugin

用于清除打包文件。在其中规定要删除的目录就可以了,删除规则可以查看官网,默认删除未使用的资源。

这个操作要放在htmlWebpackPlugin之前,也就是先删除再生成。

安装

npm i -D clean-webpack-plugin

引入

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

使用

 plugins:[
        new CleanWebpackPlugin(
        ),
        new HtmlWebpackPlugin({
            title:"kayo",
            template:'./test.html',
            filename:'index.html',
            inject: true,
            hash: true,
            chunks:['one'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        }),
        new HtmlWebpackPlugin({
            title:"kayo2",
            template:'./test.html',
            filename:'index2.html',
            inject: true,
            hash: true,
            chunks:['two'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        })
    ]

【P4】devServer与mode

4.1 devServer

devServer是一个服务器,里面的参数是一些服务器配置。

安装

npm i webpack-dev-server -D
npm i webpack-dev-server -g

参数(具体写法可以在webpack官网查看,这里只介绍一部分)

contentBase  服务器要访问的目录,会自动访问打包好的文件目录

host               服务器的ip地址

port                端口

open              自动打开页面

hot                 热更新(开发过程中,页面中有很多模块,当其中一部分模块修改时,热更新可以只刷新修改了的模块,不会整个浏览器刷新)

                      1.引入webpack模块:const webpack = require('webpack');

                      2.加入插件new webpack.HotModuleReplacementPlugin()

                      热更新的插件在webpack里,因此引入webpack,new一个热更新插件

开启服务器语法

webpack-dev-server

【为什么不进行打包,直接运行webpack-dev-server也可以正常访问页面?】因为webpack-dev-server会把输出的文件写在内存中,并且运行内存中的输出文件。

【实时更新】我们在./src/1.js中新增一些内容

console.log('第一个入口文件')
console.log('新增test') //新增

页面会自动更新:

修改模板文件也会导致自动更新

【写法小栗子】

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')

module.exports = {
    entry:{
        one:'./src/1.js', //用key:value的形式给入口文件做了命名,value是文件,key是名字
        two:'./src/2.js'
    },
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'[name].bundle.js' //[name]打包时会去找key值
    },
    plugins:[
        new HtmlWebpackPlugin({
            title:"kayo",
            template:'./test.html',
            filename:'index.html',
            inject: true,
            hash: true,
            chunks:['one'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        }),
        new HtmlWebpackPlugin({
            title:"kayo2",
            template:'./test.html',
            filename:'index2.html',
            inject: true,
            hash: true,
            chunks:['two'],
            minify:{
                collapseWhitespace: false,
                removeAttributeQuotes: true,
                removeComments: true,
            }
        }),
        new webpack.HotModuleReplacementPlugin()
    ],
    devServer:{
        host:'localhost', //启动的host
        port:8081, //启动的端口号
        open:true, //执行webpack-dev-server时自动打开页面
        hot:true //开启热更新

    }
}

 4.2 mode

mode和以上的模块同级,值是一个字符串,是webpack4.x新增的,修改了webpack3.x中的一些繁琐的工作,让这些工作更简单。

mode 模式

值为development 开发环境

本地环境

开发环境的代码不压缩,需要调试的功能

(执行webpack,生成的代码未被压缩)

 F12中sources会导出source map,可以进行断点调试

 

值为production 生产环境

打包上线的环境

生产环境的代码压缩,不需要调试的功能

(执行webpack,生成的代码被压缩)

 sources中是一行,没办法调试

 【在终端设置环境】webpack --mode

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "dev": "webpack-dev-server --mode development"
  },

-----------------------------------

先更到这里,下次继续

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值