打包工具webpack常用方法

一:安装

1.全局安装

npm i webpack -g
npm i webpack-cli -g

测试是否安装成功:

webpack --version

2.项目内安装

npm init -y
npm i webpack -D
npm i webpack-cli -D

测试是否安装成功:

在package.json 文件的scripts中加入如下代码,自定义一个版本查询命令

"version":"webpack --version"

在终端窗口里输入

npm run version

二:打包js文件

1.创建src

src文件夹,用于存储开发中的文件,

先创建一个简易js文件index.js

console.log("hello webpack")

2.项目打包指令

webpack

执行完该条指令系统会自动生成dist文件夹,main.js即为打包后的文件,

默认是production模式(压缩模式),如果不需要压缩,使用如下指令:

webpack --mode development

测试

在dist文件夹下创建index.html,引入main.js,运行index.html,main.js可以正常被加载

3.多文件打包

在src文件夹中再新建一个a.js文件

console.log("a file")

在一个index.js文件中使用import引入其他js文件,打包时一起打包,如下所示:

import "./a.js"

测试

重新运行打包指令,打开index.html,两个js文件的内容都成功加载

4.自动打包

在package.json文件的scripts部分增加自定义指令,在终端输入:npm run build  ,之后修改src内文件就会自动重新打包

    "build":"webpack --mode development -w"

5.自定义打包路径

创建 webpack.config.js文件,entry为参与打包的文件路径,mode为打包格式,output为打包完的输出配置,path为存放路径,filename为保存的文件名

const path=require("path")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle.js"
    }
}

6缓存问题

为了解决多次打包缓存问题,需要给每次生成的打包文件一个特征码,比如随机hash值,但是每次生成的文件名都不一样,手动修改效率低,所以引入html-webpack-plugin插件,先在终端窗口进行插件安装:

npm i html-webpack-plugin -D

在webpack.config.js中引入插件 

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle[hash:8].js"
    },
    plugins:[
        new HtmlWebpackPlugin()
    ]
}

每次打包之后html文件中引入的bundle.js都会更新为相应的文件名

7.模板

页面引入静态的资源文件不需要随时更新,可以通过设置html模板,指定模板路径

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle[hash:8].js"
    },
    plugins:[
        new HtmlWebpackPlugin({template:'./index.html'})
    ]
}

这样每次打包后最新的bundle.js会自动引入到dist中的index.html,原本index.html的格式也同样保留

原始的index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Webpack App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>

</html>

打包后dist中的index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Webpack App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="bundle0ddfb457.js"></script></body>

</html>

8.清除打包垃圾文件

每次打包都会生成一个js文件,但是我们只需要保存最新的即可,其他可以删除,手动删除费事,此时引入新的插件 clean-webpack-plugin,终端输入指令 npm i clean-webpack-plugin -D ,下载安装插件

npm i clean-webpack-plugin -D

webpack.config.js中修改配置

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")
const {CleanWebpackPlugin}=require("clean-webpack-plugin")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle[hash:8].js"
    },
    plugins:[
        new HtmlWebpackPlugin({template:'./index.html'}),
        new CleanWebpackPlugin()
    ]
}

之后每次打包都只会保留最新的bundle.js,之前的都会自动删除。

三.打包css文件

打包css文件需要将css转为js格式,需要借助工具 style-loader和css-loader

npm i style-loader css-loader -D

更新webpack.config.js配置文件

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")
const {CleanWebpackPlugin}=require("clean-webpack-plugin")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle[hash:8].js"
    },
    plugins:[
        new HtmlWebpackPlugin({template:'./index.html'}),
        new CleanWebpackPlugin()
    ],
    module:{
        rules:[
            {
                test:/\.css$/,
                use:['style-loader','css-loader']
            }
        ]
    }
}

在src文件夹内新建一个css文件

p{
    color: red;
}

在index.js中引入

import "./a.js"
import "./style.css"
console.log("hello webpack1")

在index.html中使用p标签

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Webpack App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <p>test</p>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>

</html>

打开index.html,可以看见样式引用成功

四.打包图片

需要安装插件:url-loader,file-loader

npm i url-loader file-loader -D

更新webpack.config.js配置

test:匹配文件格式

options:选项

limit:如果文件大小超过2000字节则独立保存,没有则打包到js文件中

outputPath:路径

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")
const {CleanWebpackPlugin}=require("clean-webpack-plugin")
module.exports ={
    entry:"./src/index.js",
    mode:"development",
    output:{
        path:path.resolve(__dirname,"dist"),
        filename:"bundle[hash:8].js"
    },
    plugins:[
        new HtmlWebpackPlugin({template:'./index.html'}),
        new CleanWebpackPlugin()
    ],
    module:{
        rules:[
            {
                test:/\.css$/,
                use:['style-loader','css-loader']
            },
            {
                test:/\.(jpg|png|gif|jpeg|svg)$/,
                use:{
                    loader:'url-loader',
                    options:{
                        limit:2000,
                        outputPath:'img/'
                    }
                }
            }
        ]
    }
}

五.webpack服务器

安装 webpack-dev-server插件

npm i webpack-dev-server -D

在package.json文件中设置启动指令

"dev":"webpack-dev-server"

启动webpack服务器

npm run dev

1.切换端口

默认端口是8080,如果需要修改,在webpack.config.js中增加配置,在port后面填写想使用的端口

    devServer:{
        port:3000
    }

2.获取数据

以获取拉勾网数据为例,先配置正向代理

devServer:{
        port:3000,
        proxy:{
            "/lg":{
                "target":"https://m.lagou.com",
                "changeOrigin":true,
                "pathRewrite":{
                    "^/lg":"/"  
                }
            }
        }
    },

安装axois

npm i axios -D

在index.js文件请求数据

import axios from "axios"
axios.get("/lg/listmore.json?pageNo=2&pageSize=15").then((res)=>{
    console.log(res)
})

浏览器访问localhost:3000,获取数据成功

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值