文章目录
webpack官方文档
1.安装webpack
终端查看版本:npm info webpack
命令安装:npm i -g webpack@4 webpack-cli@3
本地预览:webpack -dev -server
2.webpack转译成js
npm init -y
npm install webpack webpack-cli --save-dev
新建src/index.js 放上console.log(‘hi’)
./node_modules/.bin/webpack --version
npx webpack 得到main.js
//index.js
import x from './x.js'
console.log('hi')
console.log(x)
//x.js
export default 'xxx'
3.警告去除
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/configuration/mode/
webpack.config.js
var path = require('path');
module.exports = {
mode: 'production',
};
//mode可为两个值,development是详细注释,prodoction是简化版
4.webpack配置entry和output
var path = require('path');
module.exports = {
mode: 'development',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
//改成
var path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'main.js'
}
};
filename: ‘main.js’ 改成 filename: '[name].[hash].main.js’
此时npx webpack得main.34cdcb955e535284aa83.main.js
5.HTTP缓存
cache-control: public, max-age=31536000
首次访问网址下得js,css加载后缓存,二次访问直接从内存里拿
更新怎么办:文件名变化,由更新立马更新,无更新访问超快
首页index.html为什么不缓存:缓存后首页名无变化,便获取不到css、js变化
6.weback生成html页面HtmlWebpackPlugin
自动改文件名H
每次build前要删除dist文件,
需要在package.json的script里加上**“build”: “rm -rf dist&&webpack”,**
再进行 yarn build或者npm run bulid
生成HTML文件
搜webpack create html page
先保存到本地仓库,无用的放在.gitignore文件里并git commmit
yarn add html-webpack-plugin --dev
修改webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js'
},
plugins: [new HtmlWebpackPlugin()]
};
保留
var HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [new HtmlWebpackPlugin()]
yarn build得到dist里index.html
设置plugins:
[new HtmlWebpackPlugin({
title: “嘻嘻嘻”,
template: “./src/assets/index.html”,
})],
设置模板文件src\assets\index.html
手机端适配 meta name=“viewport” content=“width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no, viewport-fit=cover”>
标题title为**<%= htmlWebpackPlugin.options.title %>** (会随着webpack.config.js里title进行变化)
生成新的,存到dist文件显示的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no, viewport-fit=cover">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
</body>
</html>
7.webpack引入css
原理:css-loader把css内容读到js里,style.css把他加上style标签放在head中
把新建的css,用x.js引用
import './x.css'
引入style-loader css-loader
npm install --save-dev style-loader css-loader
加webpack.config.js内容
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
cd dist
hs -c-1预览即可
8.webpack-dev-server
原理:自动刷新,和dist文件无关,它在内存中搞定,会把index.js转译成可运行的js,放在内存中
webpack.config.js中
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
},
package.json中
"start": "webpack-dev-server --open"
"start": "webpack-dev-server"//去掉--open不会打开浏览器
npm start
9.提取css文件 MiniCssExtractPlugin
需要安装mini-css-extract-plugin
:
npm install --save-dev mini-css-extract-plugin
Minimal example
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// only enable hot in development
hmr: process.env.NODE_ENV === 'development',
// if hmr does not work, this is a forceful method.
reloadAll: true,
},
},
'css-loader',
],
},
],
},
};
给main.js加上哈希编号:
filename: '[name].[contenthash].css',
chunkFilename: '[id].[contenthash].css',
采用yarn start 替换yarn build,否则报错
10.同时用两种webpack config文件
-
复制配置文件,名称改为webpack.config.prod.js,是生产环境,设mode: “production”,
-
开发环境webpack.config.js改成use: [‘style-loader’, ‘css-loader’],style-load不用生成新文件,速度快
-
package.json为
“start”: “webpack-dev-server”,
“build”: “rm -rf dist && webpack –config webpack.config.prod.js”,
yarn start得开发环境的style标签,新建终端得yarn build的生产环境的css文件引用
11.两种webpack config文件继承简化
- …base.plugins,
- const base = require(’./webpack.config.base.js’)
webpack.config.base.js文件
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "[name].[hash].main.js",
},
plugins: [
new HtmlWebpackPlugin({
title: "喻峰",
template: "./src/assets/index.html",
}),
],
}
webpack.config.js文件
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
const base = require('./webpack.config.base.js')
module.exports = {
...base,
mode: "development",
devtool: "inline-source-map",
devServer: {
contentBase: "./dist",
},
module: {
rules: [{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}, ],
},
};
webpack.config.prod.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
const base = require("./webpack.config.base.js");
module.exports = {
...base,
mode: "production",
plugins: [
...base.plugins,
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
chunkFilename: "[id].[contenthash].css",
ignoreOrder: false,
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// only enable hot in development
hmr: process.env.NODE_ENV === "development",
// if hmr does not work, this is a forceful method.
reloadAll: true,
},
},
"css-loader",
],
},
],
},
};
12.webpack config merge 合并
https://github.com/survivejs/webpack-merge
webpack-dev-server 的作用包括
- 文件内容变化就自动转译代码,并自动刷新页面
- 提供 server 方便开发预览
- 将 JS 和 CSS 代码打包成对应的文件
webpack 的作用包括
- 将一个或多个 JS 文件打包成对应的文件
- 将一个或多个 CSS 文件打包成对应的文件
- 压缩代码
- 将高版本的 JS转译成低版本的 JS
- 提供 server 方便开发预览