这是我参与更文挑战的第6天,活动详情查看: 更文挑战
前言
最近在看vue
源码解析的教程视频,每一章讲解都使用到了webpack
,我们就要从零开始搭建脚手架,这样子太费时间了,本文将简述如何去搭建一个webpack
模板,也是方便我们后续开发或者练习时使用。(即是即拉即用,无需每次使用都去配置一遍)。
什么是webpack
webpack
是目前前端开发中最火的模块打包工具,只需要通过简单的配置,便可以完成模块的加载和打包。
我们就可以从官网中的主图看出webpack
它可以将多种文件打包合并成一个或多个bundle
。
初始化项目
npm init -y // 初始化项目
git init // 初始化git仓库
tsc --init // 生成 tsconfig.json 配置文件
复制代码
在项目中安装webpack
及webpack-cli
(本地安装)。
如果使用全局安装,这会将你项目中的
webpack
锁定到指定版本,并且在使用不同的webpack
版本的项目中, 可能会导致构建失败。
npm install webpack webpack-cli --save-dev
复制代码
配置NPM脚本
在项目的package.json
文件中的scripts对象中添加一句"build": "webpack"
,稍后我们可以使用npm run build
来把项目跑起来。
"scripts": {
"build": "webpack"
},
复制代码
项目目录结构
我们在根目录下创建一个src
,作为项目的根目录。
webpack-template
├─ src
├─ package-lock.json
├─ tsconfig.json
└─ package.json
复制代码
之后,我们在src
目录中新建一个pages
文件夹用来放置项目页面的文件夹,在pages
文件夹中创建index
文件夹及html
,scss
,ts
文件,在src
目录下创建一个main.ts
,并在main.ts
中写入。
// main.ts
console.log('main.ts')
复制代码
// 在index.ts中引入index.scss
import './index.scss'
复制代码
webpack-template
├─ src
│ ├─ pages
│ │ └─ index
│ │ ├─ index.html
│ │ ├─ index.scss
│ │ └─ index.ts
│ └─ main.ts
├─ package-lock.json
├─ package.json
└─ tsconfig.json
复制代码
创建项目配置文件
在根目录下创建一个webpack.config.ts
文件,webpack
会根据该配置文件定义的属性进行处理。
webpack-template
├─ src
│ ├─ pages
│ │ └─ index
│ │ ├─ index.html
│ │ ├─ index.scss
│ │ └─ index.ts
│ └─ main.ts
├─ package-lock.json
├─ package.json
├─ tsconfig.json
└─ webpack.config.ts
复制代码
编写config文件
// webpack.config.ts
import * as path from 'path';
import * as webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './src/main.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
clean: true,
},
};
export default config;
复制代码
在项目中执行安装命令,安装所需要用到的loader
。
npm install --save-dev css-loader style-loader sass-loader sass ts-loader typescript ts-node @types/node @types/webpack html-webpack-plugin
复制代码
在webpack.config.ts
中配置安装好的loader
和plugins
。
配置loader
loader
的一些相关配置。
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// 将 JS 字符串生成为 style 节点
'style-loader',
// 将 CSS 转化成 CommonJS 模块
'css-loader',
// 将 Sass 编译成 CSS
'sass-loader',
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
}
复制代码
配置plugins
plugins
的一些相关配置。
plugins: [
new HtmlWebpackPlugin({
title: 'index',
template: './src/pages/index/index.html',
filename: 'index.html',
}),
]
复制代码
安装后,执行npm run script
,把项目打包起来,得到dist
文件夹,里边即是我们项目中src
文件夹打包好的文件。
可以看到里边有index.html和main.js文件,由于我们写的是ts
文件,无法直接在浏览器中跑起来,上面我们配置了ts-loader
,是它帮我们把ts
转换为js
文件的。
配置多页面
为什么这里要配置多页面?
现在Vue
,React
,Angular
这三大框架都是SPA
了,开局直接npm run serve
但在很多场景下,SPA开发模式可能不太适用,比如我们学校有时候举办活动页面,或者平时写一些简单的页面,这个时候其实多页面更合适些。
因为很多时候这些页面都是完全不相关的,它们之间无需共享数据,你甚至可以对每个单独的页面使用不同的技术栈,例如页面A使用Vue,页面B使用React,页面C使用Angular,可以单独对页面设定框架的引入。
接下来,我们将把我们的webpack-template
进行多页面的配置。
将项目中的src / pages
文件夹中新建hello
文件夹,和index
一样放html
,scss
,ts
文件,这是第二个页面。
src
├─ pages
│ ├─ hello
│ │ ├─ hello.html
│ │ ├─ hello.scss
│ │ └─ hello.ts
│ └─ index
│ ├─ index.html
│ ├─ index.scss
│ └─ index.ts
└─ main.ts
复制代码
// hello.html
...
<body>
<h2>
hello.html
</h2>
</body>
...
复制代码
// hello.ts
import './hello.scss'
console.log('hello.ts');
复制代码
在webpack.config.ts
配置文件中把entry
和output
属性修改成:
entry: {
main:'./src/main.ts',
'index': './src/pages/index/index.ts', // index页面
'hello': './src/pages/hello/hello.ts', // hello页面
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name]/[name].js',
clean: true,
}
复制代码
因为多个页面对应的页面内容也是不同的,我们需要在plugins
数组上配置多个HtmlWebpackPlugin
。
属性 | 说明 |
---|---|
title | 页面标题,即document.title |
filename | 导出页面文件的名称 |
template | 页面的模板,指向pages 下对应页面的html 文件 |
chunks | 注入的脚本文件( 一定要配置这个!!否则全部脚本文件会被注入到当前页面中 ) |
关于HtmlWebpackPlugin
插件的更多配置请阅读: github.com/jantimon/ht…
plugins: [
new HtmlWebpackPlugin({
title: 'index',
filename: 'index.html',
template: './src/pages/index/index.html',
chunks: ['index','main']
}),
new HtmlWebpackPlugin({
title: 'hello',
filename: 'hello.html',
template: './src/pages/hello/hello.html',
chunks: ['hello','main']
}),
],
复制代码
现在我们再执行一下npm run build
命令,打包我们的项目。
打开hello.html
和hello.html
,我们在pages
文件夹中对应的页面文件也都被HtmlWebpackPlugin
插件处理到对应的html
文件中。
配置代码规范
具备基本工程素养的同学都会注重编码规范,而代码风格检查(Code Linting,简称 Lint)是保障代码规范一致性的重要手段,
EditorConfig
EditorConfig
是用来配置格式化代码的,这个格式化代码一定要和ESlint
中的配置相符,否则会出现格式化后的代码不符合ESlint
中的规则,从而不能正常的打包项目。
在项目根目录添加.editorconfig
文件,.editorconfig
文件是定义一些格式化规则,目录树结构这里就不放啦,太长啦!
# Editor configuration, see http://editorconfig.org
# 表示是最顶层的 EditorConfig 配置文件
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false
复制代码
提示:如果你是使用vscode
编辑器,需要到插件市场中安装 EditorConfig for VS Code
插件。
ESlint
ESlint
是一款开源的代码检查工具,找有问题的模式或者代码,并且不依赖于具体的编码风格。对大多数编程语言来说都会有代码检查,一般来说编译程序会内置检查工具。
团队开发中,团队成员之间的编码风格和习惯是不同的,我们可以使用ESlint
来解决这个问题,当代码风格不符合ESlint
规则时,就会给出代码规则提示并自动修复。让项目的编码风格统一。
安装ESlint
npm install eslint-webpack-plugin eslint --save-dev
复制代码
配置ESlint
在项目根目录中打开终端,执行npm eslint --init
,然后根据终端操作提示完成一系列设置来生成配置文件
询问你想使用ESlint检测哪些问题?
我们这里选择语法,发现问题,强制编码规范
询问你的项目使用哪种类型的模块
询问你的项目是否使用了以下框架?
我们这里选择 没有
询问你的项目是否使用了typescript?
我们这里选择 YES
询问你的代码是在哪个环境下运行的?
我们这里选择浏览器browser
询问你这么定义项目的哪种代码风格?
我们这里选择主流的样式风格
你想遵循哪一种风格?
我们这里选择Airbnb
风格
选择eslint配置文件的格式
我们这里选择 JS
文件作为它的配置文件格式
你现在想使用npm安装它们吗?
我们这里选择YES,它们将开始为我们安装这些依赖
这时候,项目根目录下自动生成了.eslintrc.js
配置文件:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb-base',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'@typescript-eslint',
],
rules: {
},
};
复制代码
在webpack.config.ts
中配置ESlint
插件,plugins
属性中添加ESLintPlugin
import ESLintPlugin from 'eslint-webpack-plugin';
// plugins
new ESLintPlugin({
extensions: ['js', 'ts'],
exclude: '/node_modules/',
}),
复制代码
提示:如果你是使用vscode
编辑器,需要到插件市场中安装 ESLint
插件并开启ESlint
服务。
测试下是否配置成功,可以在一个ts文件中,声明一个变量,不要添加分号,这个时候编辑器会显示红色波浪线来提示你。
打开在vscode
编辑器的settings.json
配置文件,添加以下代码:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
复制代码
当我们配置ESlint
之后,会弹出很多红色的波浪线,这个时候如果按上面的方法一个个去点击修复的话效率很慢,那有没有什么快捷的方法来解决这个问题呢?
sure !!
eslint
提供了--fix
选项,Automatically fix problems(自动修复问题),所以我们在package.json
中添加一个快捷脚本,自动修复src
文件夹下的后缀名为js
和ts
的文件,--ext
选项,是指定修复的目录。
"lint": "eslint --fix --ext .js,.ts src"
复制代码
执行npm run lint
,修复当前项目中所有的问题。
husky
husky 是一个 Git Hook
工具。主要实现提交前 eslint
校验和 commit
信息的规范校验。我们项目已经具有了编码规范检测,但某些时候,有可能遗漏了一两个规范警告提示,甚至是视而不见!关闭检测工具按照自己原来的编码规范来书写代码。为了解决这个问题,我们需要限制“有问题”的代码的提交,来保证GIT仓库中的代码全都是符合ESlint
规范的,这个时候我们需要用到husky
了。
执行husky-init
命令快速在项目初始化一个 husky 配置。
npx husky-init && npm install
复制代码
执行完成之后,它就配置完毕了,对的 就是这么简单。
不过,还是需要手动修改下文件的,打开.husky\pre-commit
文件,把npm test命令替换成eslint --fix --ext .js,.ts src
。
这个pre-commit
是一个hook文件,作用是当我们执行git commit
的时候,会先对项目执行一遍eslint --fix --ext .js,.ts src
,如果ESlint
通过,即commit
成功,否则停止commit
。
lint-staged
lint-staged
是一个在git
暂存文件上运行linters
的工具,当我们运行eslint
或stylelint
的命令时,只会检查我们通过git add
添加到暂存区的文件,可以避免我们每次检查都把整个项目的代码都检查一遍。
安装 lint-staged
npm i lint-staged -D
复制代码
在package.json
中添加lint-staged
配置项。
"lint-staged": {
"*.{js,ts}": "eslint --fix"
},
复制代码
这行命令表示:只对 git
暂存区的.js
、.ts
文件执行 eslint --fix
修改.husky / pre-commit
文件,把eslint --fix --ext .js,.ts src
命令替换成npx lint-staged
npx lint-staged
复制代码
最后
本文从初始化项目开始到项目结构搭建,多页面的配置再到代码提交规范这些平时常用到的一些配置选项都集成到了webpack-template
中,手把手地带领大家将一个空的文件夹构建一个前端开发项目模板,目的也是方便我们平时使用webpack
环境时,减少繁琐的配置从而节约时间。
webpack-template
GIT地址:github.com/QC2168/webp…
后面可能还会再配置一些技术栈,关注我 不迷路哦!??
码字不易,点个?吧