webpack自动打包和热更新的实现方法
curry_fe 人气:0webpack常用配置
webpack dev server
- 功能:自动打包文件
- 配置dev server:在webpack.config.client.js中配置
const path = require('path'); const HTMlPlugin = require('html-webpack-plugin'); // 判断是否是开发环境 const isDev = process.env.NODE_ENV === 'development' const config = { entry: { app: path.join(__dirname,'../client/app.js') }, output: { filename: '[name].[hash].js', path: path.join(__dirname,'..https://img.qb5200.com/download-x/dist'), publicPath: '/public' }, module: { rules: [ { test: /.jsx$/, loader: 'babel-loader' }, { test: /.js$/, loader: 'babel-loader', exclude: [ path.join(__dirname,'../node_modules') ] } ] }, plugins:[ new HTMlPlugin({ template:path.join(__dirname,'../client/template.html') }) ] } //新增 if(isDev){ // 开发环境 config.devServer = { host: '0.0.0.0',//可以使用ip访问 port:'8888', contentBase: path.join(__dirname,'..https://img.qb5200.com/download-x/dist'),//打包后的文件 overlay:{ errors:true //直接在网页上显示错误 }, publicPath:'/public', historyApiFallback:{ index:'/public/index.html' } } } module.exports = config;
在package.json中增加一条命令来进行自动打包
cross-env是为了兼容mac windows liunx的环境变量,需要安装。
npm install cross-env -D
"dev:client": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.client.js"
hot module replacemennt
功能:自动刷新页面
配置hot module:
安装react-hot-loader
npm install react-hot-loader -D
在webpack.config.client.js中配置
const webpack = require('webpack') if(isDev){ config.entry ={ app:[ "react-hot-loader/patch", path.join(__dirname,'../client/app.js') ] } ...省略 config.plugins.push(new webpack.HotModuleReplacementPlugin()) }
在client/app.js中配置
...省略 import { AppContainer } from 'react-hot-loader'; const root = document.getElementById('root') const render = Component =>{ aaa.hydrate( <AppContainer> <Component /> </AppContainer>, root ) } render(App) if(module.hot){ module.hot.accept('./App.jsx',()=>{ const NextApp = require('./App.jsx').default render(NextApp) }) }
通过以上配置就能达到局部热更新了,修改代码,页面会实时修改,不会刷新页面了。
加载全部内容