webpack基础知识学习(八)--热更新hmr

125 阅读1分钟

什么是热更新呢?他允许我们在更新模块时,页面不需要完全刷新,能做到局部刷新

webpack-dev-server配置热更新

// webpack.config.js
devServer: {
    port: 3000,
    hot: true
},

在入口文件下,添加热更新针对的模块。

src/app.js

if (module.hot) {
    module.hot.accept('./js/image.js', function() {
    console.log('Accepting the updated printMe module!');
   })
}

之后我们重新运行npm run sever

我们在index.html入口文件上添加一个输入框。

image.png

然后我们输入框输入点文字

image.png

回到代码,我们修改src/js/image.js文件里的代码,保存之后发现log保持住了,说明热更新成功!

image.png

react项目添加热更新

1.首先给我们的项目安装reactyarn add react react-dom

2.在项目中写一个react组建。

// src/react/app.jsx


import React, { Component } from "react";

export default class App extends Component {
    render() {
        return <div>我是一个react组件</div>
    }
}

3.然后在src/index.js中引入这个组件(这里对于前面的代码我做过修改了,我把webpack打包的入口文件改回index.js了,只是为了文件好看而已,也可以不改,在以前的src/app.js中引入一样的),不要忘了在public/index.html文件中加入一个idreact-root的标签。

// src/index.js

import React from 'react'
import ReactDOM from 'react-dom'

ReactDOM.render(<App />, document.getElementById('react-root'))

这样写完显然我们是没办法运行程序的,因为webpack现在还不能识别jsx文件,那怎么处理jsx文件?显然要用到babel了。我们修改webpack.config.js中对jsloader

// wenpack.config.js
// 添加了对jsx语法的支持
{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: ['babel-loader']
}

接着我们回到babel.config.js文件中,修改babel的配置。首先的安装一下对jsx处理的插件。yarn add @babel/preset-react --dev。在presets中添加插件。

presets: [
    ['@babel/preset-react']
],

这样我们就完成了针对jsx语法的处理,这时候运行npm run serve,我们的react组件就能正常显示了。

4.那怎么让react组件热更新呢?安装插件yarn add -D @pmmmwh/react-refresh-webpack-plugin react-refresh。 修改webpack.config.js中插件的配置。

// webpack.config.js
plugins: [
    new ReactRefreshPlugin()
]

修改babel.config.js中的配置。

// babel.config.js

plugins: [
    ['react-refresh/babel']
]

在重新运行npm run servereact组件就能热更新啦!

vue项目添加热更新(2+版本)

1.安装vueyarn add vue

2.在项目中写一个vue组件。

// src/vue/app.vue

<template>
    <div>
        {{title}}
    </div>
</template>

<script>
export default {
    data() {
        return {
            title: '我是一个vue组件'
        }
    }
}
</script>

<style>

</style> 

2.在src/index.js中引入vue组件。不要忘了在public/index.html文件中加入一个idvue-root的标签。

// src/index.js

import VueApp from './vue/app.vue'
import Vue from 'vue'

new Vue({
    render: h => h(VueApp)
}).$mount('#vue-root')

这时候webpack是不认识vue文件的,所以我们得添加vue的转换loader。

安装插件 yarn add vue-loader vue-template-compiler --dev.修改webpack.config.json

// webpack.config.js

const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: ['vue-loader']
            },
        ]
    },
    plugins: [
        new VueLoaderPlugin()
    ]
}

之后重新npm run serve,就发现能热更新啦!