一、Webpack 5 基础概念
Webpack 是一个现代 JavaScript 应用程序的静态模块打包工具。它会递归地构建一个依赖关系图,包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。
核心优势:
- 模块化支持:支持 ES Modules、CommonJS 等多种模块系统
- 资源处理:能够处理 JS、CSS、图片等各种资源
- 开发优化:提供热更新、代码分割等开发优化功能
二、图片资源处理
Webpack 5 引入了资源模块,取代了传统的 file-loader 和 url-loader。
基础配置:
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource', // 替换原来的file-loader
generator: {
filename: 'images/[hash][ext][query]' // 指定输出路径和文件名
}
}
]
}
}
资源模块类型:
asset/resource:发送单独文件并导出 URL(类似 file-loader)asset/inline:导出资源的 data URI(类似 url-loader)asset/source:导出资源的源代码(类似 raw-loader)asset:自动选择(默认 8kb 以下用 inline)
三、JavaScript 处理与 Babel
1. Babel 的作用
Babel 是一个 JavaScript 编译器,主要功能:
- 将 ES6+ 语法转换为向后兼容的 JS 语法
- 转换 JSX 等非标准语法
- 添加 polyfill 支持新的 API
2. 安装 Babel
npm install babel-loader @babel/core @babel/preset-env --save-dev
3. 基础配置
module.exports = {
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', {
targets: "defaults" // 根据browserslist配置自动确定需要的转换
}]
]
}
}
}
]
}
}
四、Vue 单文件组件处理
1. 安装必要依赖
npm install vue-loader@next @vue/compiler-sfc --save-dev
npm install vue@next --save
2. Webpack 配置
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
new VueLoaderPlugin() // 必须的插件
]
}
3. Vue 单文件组件示例
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello Vue!'
}
}
}
</script>
<style scoped>
.example {
color: red;
}
</style>
五、完整配置示例
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
entry: './src/main.js',
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true // 自动清理dist目录
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource'
}
]
},
plugins: [
new VueLoaderPlugin()
],
resolve: {
extensions: ['.vue', '.js'] // 自动解析的扩展名
}
}
六、开发与生产模式
package.json 配置
{
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production"
}
}
模式区别:
- development:不压缩代码,包含 source map
- production:自动启用代码压缩等优化
七、关键概念总结
| 功能 | Webpack 5 实现方式 | 说明 |
|---|---|---|
| 图片处理 | type: 'asset/resource' | 内置资源模块 |
| JS 转译 | babel-loader + @babel/preset-env | 支持最新 JS 语法 |
| Vue 组件 | vue-loader + @vue/compiler-sfc | 处理 .vue 文件 |
| 开发服务器 | webpack serve | 内置开发服务器 |