一文学会使用webpack-webpack实用篇
从0用webpack搭建一个react项目,对于一些知识点进行总结记录~
1.安装一些依赖
npm init -y // 初始化package
npm install webpack webpack-cli --save-dev // 安装webpack相关依赖
在根目录下创建 webpack.config.js文件
const path = require('path')
module.exports = { // 导出
entry: './src/index.js', // 入口
output: { // 输出
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
mode: 'production' // 模式
}
// 设置初步导出内容
在package.json中进行设置快捷打包命令
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"build": "webpack" // 运行打包
},
2.webpack基础用法
多入口文件
entry: {
app: './src/app.js',
search: './src/search.js',
},
output: {
filename: '[name].js', // 如果是多入口,则应该使用【占位符】来确保每个文件具有唯一名称
path: __dirname + '/dist',
},
bable-loader安装(根据官网文档进行配置)
解析react的jsx语法
// 通过babel官网去了解babel的一些配置https://www.babeljs.cn/docs/
npm i react-dom @babel/preset-react -D
在根目录下新建.babelrc 文件,按照官网内容进行修改
{ // 这边只是简单写一下
"presets": [
"@babel/preset-react", // 解析react语法
"@babel/preset-env"
]
}
解析css, css-loader, 解析图片,url-loader
(按照官网一步步提示即可)
监听文件(不需要每次更改文件后重新编译)(--watch)
在package.json文件中加入命令
"watch": "webpack --watch" //需要每次更新后,手动刷新浏览器
热更新HotModuleReplacementPlugin (插件)
在每次更新后,自动进行刷新
plugins: [
new webpack.HotModuleReplacementPlugin({
// Options...
})
]
// 同时增加一些devServe的配置
devServer: {
static: {
directory: path.join(__dirname, 'dist'),
},
compress: true,
port: 9000,
},
同时在package.json中增加配置 (运行过程中若有提示有包未安装,则根据提示进行安装即可)
"dev": "webpack server" // 运行
hash打包文件指纹
output: { // 输出
path: path.join(__dirname, 'dist'),
filename: '[name][chunkhash:8].js'
},
options: {
limit: 8192,
name: 'image/[name][hash:8].[ext]'
} // css loader
// [name]表示文件名 [hash:8]表示去hash前八位,md5加密后有32位 [ext表示后缀名]
// MiniCssExtractPlugin
清除构建目录,每次构建时需要手动清除dist目录,通过命令在每次构建前清除上次目录
rm -rf ./dist && webpack
rimraf ./dist && webpack
或者使用插件
new CleanWebpackPlugins()
css 浏览器兼容性,因为各大浏览器的标准还没有统一,通常处理的方法是增加相关浏览器的前缀(eg: -webkit, -ms, -moz .........),但是处理起来非常麻烦,更好的处理方式是统一的一套代码,适应不同的浏览器标准。
postcss-loader
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
[
'autoprefixer',
{
// 选项
},
],
],
},
},
// 具体内容查看官方文档进行配置
sourcemap: 对于线上代码的保护,防止业务代码泄露
Tree Shaking: 打包时去除多余代码,打包时去除没有引用的模块,当开启Mode: 'production'时就会自动开启tree shaking模式
3.代码规范:增加eslint配置
报错:error Parsing error: Unexpected token <
// eslint 配置待补充,每次配置完都在报错Parsing error: Must use import to load ES Module....
// Unexpected top-level property "parse".
//Unexpected top-level property "parse".
真的是不知道哪里有问题,把配置改了又改,还是不行,每次都在报不同的错,哭死。。。
翻看eslint官方的全英文文档又没看懂,webpack文档也没写.eslintrc配置,开始百度.......
最终好像是加了 "extends": [ 'plugin:react/recommended']终于没报错了
贴一下我的配置:
.eslintrc
// .eslintrc
module.exports = {
"env": {
"node": true,
"browser": true
},
"plugins": [
"html",
"react",
"react-hooks"
],
"extends": [ 'plugin:react/recommended',"eslint:recommended"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"no-var": "error",
"no-console": "warn"
}
}
webpack.config.js
// webpack.config.js
const ESLintWebpackPlugin = require('eslint-webpack-plugin')
new ESLintWebpackPlugin({
context: path.resolve(__dirname, 'src')
}),
package.json
// package.json
"eslintConfig": {
"parser": "babel-eslint"
}
webpack-bundle-analyzer: 压缩打包内容
4.自己编写一个插件:
class MyPlugins() {
apply(compiler) { // 每个插件都需要有该方法
compiler.hooks.done.tap ( 'My Plugins', (states) => {
}))
}
}
module.exports = MyPlugins
// 插件使用
require('../') // 引入
plugins: [ new MyPlugins()]
5.记录:
1.react18中引入节点的方式进行改变
// 原先
import ReactDOM from 'react-dom';
ReactDOM.render(
<Index />,
document.getElementById('root')
)
// react18
import ReactDOM from 'react-dom/client';
ReactDOM.createRoot(
document.getElementById('root')
).render(<Index />);
2.运行后一直报错
Uncaught Error: createRoot(...): Target container is not a DOM element.
感觉一直有Index.html,但是不知道为什么找不到根节点
解决方案
// 解决方案:
new HtmlWebpackPlugin({
template: './src/index.html',
title: 'Test',
}),
6.贴一下所有实现代码
目录结构
webpack.config.js
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintWebpackPlugin = require('eslint-webpack-plugin')
module.exports = { // 导出
entry: './src/index', // 入口
output: { // 输出
path: path.join(__dirname, 'dist'),
filename: '[name][chunkhash:8].js'
},
mode: 'development', // 模式
module: {
rules: [
{
test: /.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /.less$/i,
use: [
// compiles Less to CSS
'style-loader',
'css-loader',
'less-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
[
'autoprefixer',
{
// 选项
},
],
],
},
}
}
],
},
{
test: /.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: 'image/[name][hash:8].[ext]'
}
},
],
type: 'javascript/auto'
},
]
},
devServer: {
static: {
directory: path.join(__dirname, 'dist'),
},
compress: true,
port: 9000,
},
plugins: [
new ESLintWebpackPlugin({
context: path.resolve(__dirname, 'src')
}),
new webpack.HotModuleReplacementPlugin({
// Options...
}),
new HtmlWebpackPlugin({
template: './src/index.html',
title: '小程序服务后台',
}),
]
}
.babelrc
{
"presets": [
"@babel/preset-react", // 解析react语法
"@babel/preset-env"
]
}
package.json部分代码
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"build": "webpack",
"watch": "webpack --watch",
"dev": "webpack server"
},
总结:
这边只是基本的一个对于webpack的搭建,适用于新手入门使用
后面将对webpack文档通读一下,再总结一下,学习很多,其实对照着官方文档一步步阅读学习能快速成长,官方文档yyds
可能文档中会有一些错误或不明白的地方,欢迎指出
可以关注我的个人公众号《七月记录生活》,记录生活,共同成长!!!
五一即将到来,在文章的最后祝愿大家五一快乐!!!!!
生活不止眼前的苟且还有诗和远方的田野,完结撒花~~~
转载自:https://juejin.cn/post/7226181070201831479