从零搭建react框架(二)
1.项目静态文件打包配置
图片文件打包配置
安装依赖包
yarn add url-loader url-loader
webpack.config.js
{ test: /\.(png|jpg|gif|woff|svg|ttf|eot)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8192,
outputPath: './assets/img/', // 打包图片位置
name:'[name]-[hash:5].min.[ext]'
}
}]
}
针对url图片配置
安装依赖包
yarn add copy-webpack-plugin
webpack.config.js
plugins: [ new CopyWebpackPlugin([{
from: path.resolve(__dirname, 'src/assets/'),
to: path.resolve(__dirname, 'dist/assets/')
}])
],
打包结果
sass、css文件打包配置
安装依赖包
yarn add node-sass sass-loader style-loader css-loader mini-css-extract-plugin
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 在生产环境将样式表抽成单独的文件,不依赖jsconst devMode = process.env.NODE_ENV !== 'production';
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
})
],
{
test: /\.scss$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
]
},
src/app.js
import React from 'react';import ReactDom from 'react-dom';
import './assets/style/app.scss';
ReactDom.render(
<div>
react is building
<img src="./assets/img/app.jpg" alt=""/>
</div>,
document.querySelector("#app"));
在src/assets目录下新建img/app.jpg、style/app.scss文件,yarn start
启动项目
2.项目热加载配置
开发人员修改了代码,经过webpack打包后,只替换修改的部分代码,做到页面的局部刷新,不会改变react其他未修改的状态和数据
安装依赖包
yarn add react-hot-loader
/src/route/index.js
import React from 'react';import {Switch, BrowserRouter, Route} from 'react-router-dom';
import {hot} from 'react-hot-loader';
import Index from '../views/Index';
import User from '../views/User';
import Count from '../views/Count';
const BasicRoute =() => (
<BrowserRouter>
<Switch>
<Route exact component={Index} path="/"/>
<Route exact component={User} path="/user"/>
<Route exact component={Count} path="/count"/>
</Switch>
</BrowserRouter>
);
export default hot(module)(BasicRoute);
至此,react框架的开发环境基本搭建完成了(* ̄︶ ̄)。接下来需要做一些优化、拆分出生产环境需要的配置
项目github地址:https://github.com/kakaoG/react-webpack
以上是 从零搭建react框架(二) 的全部内容, 来源链接: utcz.com/z/382699.html