1. 程式人生 > >Vue核心技術-60,Vuex-熱過載

Vue核心技術-60,Vuex-熱過載

一,前言

本編簡單介紹Vuex熱過載,使用webpack提供的HMR實現
先將蒐羅到的配置列出來,後續在做補充

二,熱過載

使用webpack的熱模替換(HMR)外掛(Hot Module Replacement API)
Vuex支援在開發過程中熱過載mutation、module、action和getter

對於mutation和模組,需要使用store.hotUpdate()方法:

src/store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters'
import * as actions from './actions' import * as mutations from './mutations' Vue.use(Vuex) const state = { count: 0, history: [] } const store = new Vuex.Store({ state, getters, actions, mutations }) if (module.hot) { module.hot.accept([ './getters', './actions', './mutations'
], () => { store.hotUpdate({ getters: require('./getters'), actions: require('./actions'), mutations: require('./mutations') }) }) } export default store

webpack配置檔案:webpack.config.js

const fs = require('fs')
const path = require('path')
const webpack = require('webpack'
) const VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { mode: 'development', entry: fs.readdirSync(__dirname).reduce((entries, dir) => { const fullDir = path.join(__dirname, dir) const entry = path.join(fullDir, 'app.js') if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) { entries[dir] = ['webpack-hot-middleware/client', entry] } return entries }, {}), output: { path: path.join(__dirname, '__build__'), filename: '[name].js', chunkFilename: '[id].chunk.js', publicPath: '/__build__/' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: /\.vue$/, use: ['vue-loader'] }, { test: /\.css$/, use: ['vue-style-loader', 'css-loader'] } ] }, resolve: { alias: { vuex: path.resolve(__dirname, '../src/index.esm.js') } }, optimization: { splitChunks: { cacheGroups: { vendors: { name: 'shared', filename: 'shared.js', chunks: 'initial' } } } }, plugins: [ new VueLoaderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ] }