隐藏侧边栏

什么是webpack

  • 一、webpack是什么

    webpack 是一个用于现代 JavaScript 应用程序的静态模块化打包构建工具

    模块化:服务端Common.js(module.exports,require),浏览器端ES Module(export,export default,import {} from xxx)

    src目录 你写的源代码

    

1
2
3
npm run build
 
dist--index.html,js css

 

  • 二、webpack快速使用

    2.1 初始化package.json

   

1
npm init -y

 


    2.2 安装webpack相关依赖

   

1
npm i webpack webpack-cli -D

 

  • 2.3 写一点点测试代码   
1
2
3
src index.js,tools.js
 
public index.html 引入dist/main.js

 

  • 2.4 在package.json中添加打包脚本
1
2
3
4
5
6
7
{
....
"scripts": {
"build":"webpack"
},
...
}

 

  • 2.5 编写webpack配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
编写webpack配置文件,让webpack实现灵活环境定制,如下:
 
//引入相关依赖
const webpack = require('webpack')
const path=require('path')
//创建一个webpak配置对象
const config = {
//设置模式
mode:'development',
//配置入口
entry:'./src/main.js',
//配置出口
output: {
//打包路径
path:path.resolve(__dirname,'dist'),
//打包文件名
filename: 'js/bundle.js',
//清理无用文件
clean:true
 
}
}
//抛出对象
module.exports=config

 

  • 2.6 安装webpack服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
安装webpack-dev-server: npm i webpack-dev-server -D
 
配置webpack.config.js
 
{
....
//配置webpack服务器
devServer: {
port: 9999,
//静态目录位置
static: {
directory:'dist'
}
}
....
}
配置package.json运行脚本
 
{
...
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
...
}

 

  • 2.7 自动注入html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
安装html-webpack-plugin: npm i html-webpack-plugin -D
 
配置webpack.config.js
 
//引入相关依赖
const webpack = require('webpack')
const path = require('path')
//引入html-webpack-plugin
const HtmlWebpackPluin=require('html-webpack-plugin')
//创建一个webpak配置对象
const config = {
//设置模式
mode:'development',
//配置入口
entry:'./src/main.js',
//配置出口
output: {
//打包路径
path:path.resolve(__dirname,'dist'),
//打包文件名
filename: 'js/bundle[contenthash].js',
//清理无用文件
clean:true
 
},
//配置插件
plugins: [
new HtmlWebpackPluin({
//从哪个模板生成html
template:'./public/index.html',
//生成后的html文件名
filename:'index.html'
})
],
//sl
//配置webpack服务器
devServer: {
port: 9999,
//静态目录位置
static: {
directory:'dist'
}
}
}
//抛出对象
module.exports=config

 

posted @   阴茵  阅读(124)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
  
欢迎阅读『什么是webpack』
  
  
                                     
点击右上角即可分享
微信分享提示