小白入门级别的webpack实践,搭建一个基础的webpack
项目地址:git@github.com:Oldpost/webpack-tes…
原文地址:blog.silviaxu.com/2019/04/08/…
安装
全局
npm install webpack –g
本地
npm install webpack –save-dev
测试
webpack -v
准备工作
新建一个空项目并初始化,创建一个dist/index.html和index.js
mkdir webpack-test
cd webpack-test
npm init
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack test</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
index.js
document.write('今天天气很好')
开始第一个webpack
命令行执行
webpack index.js bundle.js
报错
webpack index.js -o bundle.js
- Hash:hash值
- Version:webpack版本
- time:这次打包所花费的时间
- Asset:打包这次生成的文件
- Size:这次生成文件的大小
- Chunks:这次打包的分块
- chunk Names:这次打包的名称
此时警告:
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
是因为webpack4引入了模式,有开发模式,生产模式,无这三个状态。暂时可忽略。
此时打包完成,打开dist文件夹下,可以看到打包好的bundle.js文件
通过配置文件打包以及开发
新建webpack.config.js文件,并在package.json文件里配置scripts字段
"build": "webpack --mode production"
webpack.config.js需要配置其文件的入口及出口
const path = require('path');
module.exports = {
entry:"./src/index.js",
output:{
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module:{
rules:[
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
},
plugins:[]
}
path 是一个 Node.js 核心模块,用于操作文件路径。entry:入口的文件,即要处理的文件(现在只做单个入口)、output:出口的文件,可配置出口文件路径以及文件相关信息、module:即配置 loader,可以通过配置 loader 扩展其他语言,如scss、plugins:插件
命令行运行:
npm run build
此时打包完成,打开dist文件夹下,可以看到打包好的bundle.js文件
开发过程
在开发过程中为了避免改一点代码就运行一次命令,加入开发模式。 首先需要安装webpack-dev-server
npm install --save-dev webpack-dev-server
在package.json文件里配置scripts字段
"start": "webpack-dev-server --mode development --open",
--open:自动打开窗口
// webpack.config.js需要配置 devServer
module.exports = {
...
devServer: {
contentBase: path.join(__dirname, "dist"),
hot: true, // 开启实时刷新
port: 9000 // 端口,默认8080
}
}
错误追踪
为了更容易地追踪错误和警告,JavaScript 提供了 source map 功能,将编译后的代码映射回原始源代码。如果一个错误来自于 b.js,source map 就会明确的告诉你。在package.json文件里配置,
devtool: 'inline-source-map',
动态页面
通常我们需要开发一个动态的html文件,而不是直接在dist文件夹里面放进去一个静态文件。这里使用到 html-webpack-plugin 插件
npm install --save-dev html-webpack-plugin
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 动态生成html文件
module.exports = {
...
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),
})
],
}
编译文件前清空dist
npm install --save-dev clean-webpack-plugin
webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin'); // 动态生成html文件
module.exports = {
...
plugins: [
new CleanWebpackPlugin(),
],
}
哈希值
可以在 output 里配置输出文件的文件名。当文件变化的时候加载新文件 否则使用缓存
module.exports = {
...
output:{
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.[chunkhash].js'
},
}
- hash:hash值是特定于整个构建过程的
- chunkhash:hash值是特定于每一个文件的内容的
图片
npm install url-loader file-loader html-withimg-loader --save-dev
- url-loader: 功能类似于 file-loader,但是在文件大小(单位 byte)低于指定的限制(limit)时,可以返回一个 DataURL
- file-loader:直接将图片打包到生产目录下
- html-withimg-loader:处理html中直接使用src引用的img 使用相对路径
// index.html
<img src="images/750x380.cc8da272.png" alt="" sizes="" srcset="">
webpack.config.js配置
module.exports = {
...
module:{
rules:[
...
{
test: /\.(png|jpg)$/,
use: [{
loader: 'url-loader',
// 将小于8K的图片以base64的形式打包到js文件中
options: {
limit: 8192, // 文件大小
name: '[name].[hash:8].[ext]', // 设置文件名
// name(file) {
// if (process.env.NODE_ENV === 'development') {
// return '[path][name].[ext]';
// }
// return '[hash].[ext]';
// },
outputPath: 'images', // 新增一层文件路径
}
}],
},
{
test: /\.html$/,
loader: 'html-withimg-loader'
}
]
}
}
name:当配置为 [path][name].[ext] 时,会将路径也一并打包, ext:目标文件/资源的文件扩展名。 path:相对于webpack/config 文件的路径 outputPath: 指定文件路径
css 分离打包
webpack4之前使用 extract-text-webpack-plugin,现在用 mini-css-extract-plugin 代替
npm install --save-dev mini-css-extract-plugin
webpack.config.js配置
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // webpack分离css单独打包
module.exports = {
...
module:{
modules:[
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
}
},
// 在这里带调用 style-loader 会报错
"css-loader"
]
// use: ['style-loader', 'css-loader'] // 先调用css-loader,解决不了在调用style-loader
},
...
]
plugins:[
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
}