-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
从零开始配置webpack react开发环境 #2
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
首先初始化项目
1. 安装webpack
要安装最新版本或特定版本,请运行以下命令之一:
如果你使用 webpack 4+ 版本,你还需要安装 CLI。
2. 新建文件目录
3. 配置加载器
3.1 构建简单的webpack.common.js配置文件
根据上述文件目录结构,新建配置文件
public/webpack.common.js
在
packge.json
添加尝试运行
npm run dev
webpack
告诉我们需要使用加载器来处理该文件,针对 react 文件,需要使用babel-loader
,对于其他的格式文件,需要进行配置。由于配置中会用到一些工具,所以新建
/build/util.js
,引入util.js
3.2 配置babel-loader
在
webpack.config.js
添加 babel 配置3.3 配置.css .scss文件 loader
sass-loader
css-loader
style-loader
sass-loader
依赖node-sass
,由于这个包存放在 github 上,下载速度比较慢,可使用淘宝源下载在
webpack.config.js
rules 添加配置3.4 配置图片文件的加载
关于图片或文件的相关
loader
:file-loader
默认情况下,生成的文件的文件名就是文件内容的 MD5 哈希值并会保留所引用资源的原始扩展名。url-loader
功能类似于 file-loader,但是在文件大小(单位 byte)低于指定的限制时,可以返回一个 DataURL。url-loader
依赖file-loader
这里选择使用
url-loader
在
webpack.config.js
rules 添加配置4. 开发环境构建
区分
production
和development
环境下的配置4.1 安装相关功能依赖
loader
配置中MiniCssExtractPlugin.loader
与style-loader
不能同时使用。修改
webpack.common.js
分别添加
webpack.prod.js
webpack.dev.js
文件webpack.prod.js
webpack.dev.js
4.2 修改scripts
现在执行
npm run dev
将会得到一个简单的开发环境5. 功能的进一步完善
到此为止我们完成了一个简单的配置,在开发环境下实现热重载、加载样式文件,生产环境下代码压缩、自动拷贝
index.html
并注入script
、打包自动清理dist
文件夹。下面继续完善相关的功能。5.1 配置devserver
配置如下,命令行只显示警告或错误信息,同时使用
friendly-errors-webpack-plugin
插件,自动清除信息,并自定义显示信息内容。webpack.dev.js
5.2配置buils.js文件
安装依赖
新建
build/build.js
,修改scripts.build
cross-env NODE_ENV=production node ./build/build.js
,ora
能在命令行显示的加载动画,chalk
能够输出带有颜色的文字或消息。5.3 本机地址访问
首先需要获取本机地址,
nodejs
os
模块提供了相关的功能。build/util.js
修改
devServerConfig.host
为'0.0.0.0'
,再修改FriendlyErrorsPlugin
配置/build/webpack.dev.js
5.4 添加eslint
具有完备的
eslint
配置可以极大程度上规范编码格式,同时配合编辑器的保存自动根据配置修复,开发体验较好,如果不想使用eslint
可以在webpack.dev.js
中设置(不推荐)安装相关插件
eslint-loader
配合eslint-friendly-formatter
能够在编译时将代码与eslintrc
冲突的错误显示在命令行修改webpack.common.js
The text was updated successfully, but these errors were encountered: