提示:本文篇幅较长,请耐心看完哦~
本篇文章是介绍基于React和webpack搭建的一套完整项目流程,目标是搭建一个可用的脚手架,在此基础上可以扩展出更多的功能。
架构需要支持的特性:
1.Webpack5
2. es6+
3. React
4. Typescript
5. PostCSS + cssnext
6. HMR
一、项目创建
1.安装webpack
新建一个文件夹即项目文件(react_webpack),进入根目录,输入yarn init -y 会自动生成package.json文件。
yarn init -y
如下图所示:
这是我个人搭建项目正常的文件存放格式
dist:打包输出文件夹
pubilc中的index.html:入口html文件
assets:存放图片,字体和icon的
components:存放封装的公共组件
utils:存放全局封装的js文件
pages:页面相关文件
app.js:全局js文件,配置相关
2.安装webpack(模块打包库)和webpack-cli(命令行工具)
yarn add webpack webpack-cli -D
或
npm i webpack webpack-cli -D
3.webpack基础配置:
进入项目根目录,创建文件webpack.config.js
1.entry入口文件
webpack会首先从这里开始编译
// webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: './src/index.js'//入口文件
},
}
2.ouput
定义了打包后输出的位置,以及对应的文件名。[name]是一个占位符,这里是根据我们在entry中定义的key值,即等价于app
// webpack.config.js
const path = require('path');
module.exports = {
/*...*/
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js',
},
}
3.yarn run build
根目录下创建src文件夹,在src文件夹下创建index.js文件,在package.json中加入以下代码,运行命令yarn run build,现在就可以使用我们的最小化配置进行打包了。
yarn run build
"scripts": {
"build": "webpack"
}
运行成功之后我们可以看到根目录下出现dist文件夹,说明打包成功
4.plugins
插件使webpack具备可扩展性,可以让我们支持更多的功能。
当我们构建一个web app的时候,我们需要一个HTML页,然后再HTML中引入Javascript,当我们配置了打包输出的bundle文件是随机字符串时,每次手动更新就特别麻烦,所以最好的方法是可以自动将bundle打包进HTML中。
Html-webpack-plugin - 从模板生成一个HTML文件
安装
yarn add html-webpack-plugin --save
或
npm i --save -dev html-webpack-plugin
根目录下新建文件夹public,并在public下新建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
其中title是读取html-webpack-plugin插件的配置, webpack.config.js文件配置如下
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
/*...*/
plugins: [
new HtmlWebpackPlugin({
title: "我是网页",
template: path.resolve(__dirname, "./public/index.html"),
filename: "index.html",
}<