使用 npm 安装 Webpack 和 Webpack CLI:
npm install --save-dev webpack webpack-cli
基础配置
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
}
};
然后运行 Webpack:
npx webpack --config webpack.config.js
使用插件
Webpack 提供了丰富的插件系统,可以实现各种功能扩展。以下是一个使用 HtmlWebpackPlugin 的示例:
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
};
Entry:配置入口文件,Webpack 会从这些入口文件开始构建依赖图。
module.exports = {
entry: './src/index.js',
};
Output:配置输出文件的名称和路径。
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Loaders:定义模块的转换规则,例如处理 CSS 文件或图像文件。
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
};
Plugins:扩展 Webpack 的功能,例如 HtmlWebpackPlugin、CleanWebpackPlugin 等。
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
Mode:指定当前构建环境,可以是 development
、production
或 none
。
module.exports = {
mode: 'development'
};
代码拆分 (Code Splitting)
代码拆分有助于减少初始加载时间,可以通过动态导入来实现:
// src/index.js
import('./module').then(module => {
// 使用模块
});
热模块替换 (HMR)
热模块替换允许在应用程序运行时替换、添加或删除模块,而无需重新加载整个页面:
// webpack.config.js
const webpack = require('webpack');
module.exports = {
devServer: {
contentBase: './dist',
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
使用 TypeScript
Webpack 也可以用于打包 TypeScript 项目,使用 ts-loader
:
// webpack.config.js
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
Webpack 是一个功能强大且灵活的工具,通过其丰富的插件和 loader 系统,可以处理各种复杂的前端构建需求,并优化应用的性能和加载速度,更多信息可以访问官网。