当前位置:网站首页>weback5基础配置详解
weback5基础配置详解
2022-07-01 07:11:00 【柯晓楠】
1、安装
命令:
npm init -y
npm install webpack webpack-cli --save-dev
在项目的根目录下启动 cmd,执行 webpack 命令会出现不是内部或外部命令(因为是本地安装),可以执行以下命令构建:
npx webpack
2、配置
webpack.config.js配置文件
在项目根目录下创建 webpack.config.js 文件,配置内容如下:
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
},
mode: 'development'
}
在 package.json 中配置 npm script 脚本:
{
"scripts": {
"build": "webpack"
}
}
此时,打包命令如下:
npm run build
插件
以 html-webpack-plugin 为例,安装:
npm install html-webpack-plugin --save-dev
在 webpack.config.js 文件添加以下配置:
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
clean: true // 清除旧的打包文件
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html', // 模板位置
filename: 'index.html', // 打包后的html文件名称
inject: 'body' // script标签位置,可选值:body/head
})
]
}
需要在项目根目录创建 index.html 模板文件。
设置 mode 模式
开发模式
module.exports = {
mode: 'development'
}
生产模式
module.exports = {
mode: 'production'
}
区别:开发模式打包的 .js 文件没有压缩,并且显示详细信息;开发模式打包的 .js 文件是压缩后的文件
源代码调试
代码异常时定位到源码,在 webpack.config.js 文件中配置:
module.exports = {
devtool: 'inline-source-map'
}
devtool 字段的模式包括:
| 模式 | 说明 |
|---|---|
eval | 每个 module 会封装到 eval 里包裹起来执行,并且会在末尾追加注释 //@ sourceURL |
source-map | 生成一个 SourceMap 文件 |
inline-source-map | 生成一个 DataURL 形式的 SourceMap 文件 |
hidden-source-map | 和 source-map 一样,但不会在 bundle 末尾追加注释 |
eval-source-map | 每个 module 会通过 eval() 来执行,并且生成一个 DataURL 形式的 SourceMap |
cheap-source-map | 生成一个没有列信息(column-mappings)的 SourceMaps 文件,不包括 loader 的 sourcemap (譬如 babel 的 sourcemap) |
cheap-module-source-map | 生成一个没有列信息(column-mappings)的 SourceMap 文件,同时 loader 的 sourcemap 也被简化为只包含对应行的 |
动态编译
修改 package.json 中的 npm script 脚本:
{
“scripts”: {
"build": "webpack --watch"
}
}
本地服务器
安装:
npm install webpack-dev-server --save-dev
配置 npm script :
{
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack --watch"
}
}
启动服务:
npm run dev
在浏览器中访问项目 http://127.0.0.1:8080/
配置默认打开浏览器:
{
"scripts": {
"dev": "webpack-dev-server --open",
}
}
webpack.config.js 文件配置本地服务器:
const path = require('path')
module.exports = {
devServer: {
static: path.resolve(__dirname, './dist'),
compress: true, // 服务器端是否进行代码压缩,传输 zip 压缩包
port: 8080, // 端口号
host: '0.0.0.0', //
headers: {
// 配置响应头
'X-Access-Token': 'xxx'
},
proxy: {
'/api': {
target: 'http://192.168.1.100:3000', // 真实的服务器地址
pathRewrite: {
'^/api': ''
}
}
},
https: {
// 配置HTTPS证书
cacert: './server.pem',
pfx: './server.pfx',
key: './server.key',
cert: './server.crt',
passphrase: 'webpack-dev-server',
requestCert: true
},
historyApiFallback: true, // 配置 SPA 应用的 history 路由模式
hot: true, // 模块热替换
liveReload: true, // 开启热更新
}
}
加载资源
(1)resource资源
// webpack.config.js
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
clean: true,
assetModuleFilename: 'image/[contenthash][ext]' // 自定义静态资源打包目录与名称
},
module: {
rules: [
{
test: /\.jpg|\.png$/,
type: 'asset/resource', // 发送一个单独文件的URL
generator: {
filename: 'images/[contenthash][ext]' // 优先级高于 output.assetModuleFilename
}
}
]
}
}
(2)inline资源
不会打包出任何静态资源文件
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jpg|\.png$/,
type: 'asset/inline' // 导出一个资源的Data URI,页面中的图片为 base64
}
]
}
}
(3)source资源
不会打包出任何静态资源文件
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/,
type: 'asset/source' // 导出资源的源代码
}
]
}
}
通用资源类型 asset,在导出一个 data URI 和发送一个单独的文件之间自动选择。
默认地,当文件小于 8kb 时,将会被视为 inline 模块类型,否则会被视为 resource 模块类型。可以在 module rule 层级中,设置 Rule.parser.dataUrlCondition.maxSize 选项来修改条件。修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 200 * 1024 // 小于200kb是为 inline 模式
}
}
}
]
}
}
加载CSS
需要安装 css 相关的 loader:
npm install css-loader style-loader --save-dev
css-loader 用于编译 css 文件,style-loader 用于将 css 代码加载到 .html 模板文件中。
配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
}
]
}
}
在项目中引入 sass,安装 sass 和 sass-loader:
npm install sass sass-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
}
]
}
}
要以模块化的方式将
.css和.scss样式文件引入.js文件中
抽离 CSS
需要安装插件:
npm install mini-css-extract-plugin --save-dev
mini-css-extract-plugin插件最小支持webpack5版本
修改配置文件:
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: 'style/[contenthash].css'
})
],
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
}
]
}
}
压缩 CSS
安装插件:
npm install css-minimizer-webpack-plugin --save-dev
修改配置文件:
// webpack.config.js
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
module.exports = {
mode: 'production',
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
}
配置完成后,执行构建命令 npm run build, 打包后的 css 代码就被压缩了。
加载 fonts 字体
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
type: 'asset/resource'
}
]
}
}
加载数据
(1)加载 csv 、tsv 文件
安装:
npm install csv-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(csv|tsv)$/,
use: ['csv-loader']
}
]
}
}
(2)加载 xml 文件
安装:
npm install xml-loader --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.xml$/,
use: ['xml-loader']
}
]
}
}
(3)加载 yaml 文件
安装依赖:
npm install yaml --save-dev
修改配置文件:
// webpack.config.js
const yaml = require('yaml')
module.exports = {
module: {
rules: [
{
test: /\.yaml$/,
type: 'json',
parser: {
parse: yaml.parse
}
}
]
}
}
(4)加载 toml 文件
安装依赖:
npm install toml --save-dev
修改配置文件:
// webpack.config.js
const toml = require('toml')
module.exports = {
module: {
rules: [
{
test: /\.toml$/,
type: 'json',
parser: {
parse: toml.parse
}
}
]
}
}
(5)加载 json5 文件
webpack 默认可以编译 json 文件,如果使用了升级版的 .json5 文件,需要安装依赖:
npm install json5 --save-dev
修改配置文件:
// webpack.config.js
const json5 = require('json5')
module.exports = {
module: {
rules: [
{
test: /\.json5$/,
type: 'json',
parser: {
parse: json5.parse
}
}
]
}
}
ES6转ES5
将 ES6 代码转为 ES5 代码需要 babel-loader 加载器,其中:
babel-loader:在webpack中应用babel解析ES6的桥梁;@babel/core:babel核心模块;@babel/preset-env:babel预设,一组babel插件的集合。
安装:
npm install babel-loader @babel/core @babel/preset-env --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
还需要再安装 regeneratorRuntime 插件,它是 webpack 打包生成的全局辅助函数,有 babel 生成,用于兼容 async/await 语法。
安装插件:
# 生产环境运行时需要这个插件,要安装到生产环境依赖
npm install @babel/runtime --save
# 编译时需要在使用 regeneratorRuntime 的地方自动 require 导包
npm install @babel/plugin-transform-runtime --save-dev
修改配置文件:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [
['@babel/plugin-transform-runtime']
]
}
}
}
]
}
}
配置 eslint
安装 eslint
npm install eslint --save-dev
初始化 .eslintrc 文件,执行以下命令自定生成:
npx eslint --init
在控制台中选择如下:
$ npx exlint --init
√ How would you like to use ESLint? · style
√ What type of modules does your project? · esm
√ Which framework does your project use? · none
√ Does your project use TypeScript? · No
√ Where does your code run? · browser
√ How would you like to dofine a sytle for your project? · guide
√ Which style guide do you want to follow? · airbnb
√ What format do you want your config file to be in? · JSON
.eslintrc 文件的默认配置如下:
env:设置脚本的运行环境;extends:继承社区整理好的配置规则,例如eslint-plugin-react/recommended使用社区的react规则;plugins:添加的插件,为eslint增加新的检查规则,例如eslint-plugin-react是对react项目的检查规则;parser:配置解析项目的规则,例如@typescript-eslint/parser;parserOptions:搭配parser,指定需要支持的javascript语言选项;globals:当访问当前源文件内未定义的变量时,no-undef规则将发出警告。如果你想在一个源文件里使用全局变量,推荐你在ESLint中定义这些全局变量,这样ESLint就不会发出警告了;readonly表示可读不可写,writable表示可读可写;rules:具体的规则,off 或 0 表示关闭规则;warn 或 1 表示使用警告级别开启规则(不会退出程序);error 或 2 表示使用错误级别开启规则(触发规则会退出程序)。
结合 webpack 使用
安装:
npm install eslint-loader --save-dev
修改 webpack.config.js 文件:
module.exports = {
module: {
rules: [
{
test: /\.(js | jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
}
]
},
devServer: {
client: {
overlay: true // 默认为true,即开启热更新功能
}
}
}
边栏推荐
- 如何制作专属的VS Code主题
- LeetCode+ 71 - 75
- Router 6/ and the difference with router5
- 在券商账户上买基金安全吗
- Paging in servlets and JSPS
- 8 figures | analyze Eureka's first synchronization registry
- Problem: officeexception: failed to start and connect (III)
- K8s set up redis cluster
- [image processing] image histogram equalization system with GUI interface
- 【剑指offer&牛客101】中那些高频笔试,面试题——链表篇
猜你喜欢

How to enter the Internet industry and become a product manager? How to become a product manager without project experience?

Is it suitable for girls to study product manager? What are the advantages?

Jena default inference query based on OWL

How to draw a product architecture diagram?

Mysql与Redis一致性解决方案

【LINGO】求七个城市最小连线图,使天然气管道价格最低

Code practice - build your own diffusion models / score based generic models from scratch

Are there any practical skills for operation and maintenance management

8 figures | analyze Eureka's first synchronization registry

Solve the problem of "unexpected status code 503 service unavailable" when kaniko pushes the image to harbor
随机推荐
K8s set up redis cluster
【FPGA帧差】基于VmodCAM摄像头的帧差法目标跟踪FPGA实现
Image style migration cyclegan principle
The game is real! China software cup releases a new industrial innovation competition, and schools and enterprises can participate in it jointly
5G Massive MIMO的概念和优点总结
【分类模型】Q 型聚类分析
8 figures | analyze Eureka's first synchronization registry
Rclone configuring Minio and basic operations
用手机在指南针上开户靠谱吗?这样有没有什么安全隐患
The programmer of Beipiao posted a post for help late at night: I am lonely when my girlfriend is gone
DC-4靶机
解决无法读取META-INF.services里面定义的类
Webapck packaging principle -- Analysis of startup process
熱烈祝賀五行和合酒成功掛牌
Solution to the problem that objects in unity2021 scene view cannot be directly selected
灰度何以跌下神坛?
JSP - paging
C语言实现【扫雷游戏】完整版(实现源码)
【系统分析师之路】第五章 复盘软件工程(逆向净室与模型驱动开发)
atguigu----脚手架--02-使用脚手架(2)