webpack-context-hmr
tl;dr
This module makes it easy to setup dynamic imports of javascript modules using require.context
and removes the need for the extra boilerplate that is needed to make HMR work with them.
To see this plugin in action, clone, download and run: webpack-context-hmr-demo
Introduction
Some frameworks requires application modules to be imported into main.js
and registered into the framework in some way. Example of this are Vuex modules.
This package uses Webpack's require.context
to dynamically load all modules matching a regex and takes care of the necessary boilerplate to make HMR work with the dynamic context. The hmrSetup
takes a callback function that should handle framework specific hot updates.
For vuex, there is a more specific version that makes things even easier: Webpack-context-vuex-hmr.
Submodules:
When working with submodules/substores and Webpack 1
, this loader in needed: hmr-auto-accept-loader
This loader is not needed with Webpack 2
.
Usage
Require.context
cannot handle runtime input. It can however be configured by using the ContextReplacementPlugin
.
Configure the importer by adding the plugin to the webpack configuration:
plugins: new /webpack-context-hmr$/ // [leave me] this file path // [edit me] context root path true // [edit me] recursive search /-store.js|-substore.js$/ // [edit me] regexp to find modules
In this example the importer will look in <project-path>/src
using recursive search through folders, looking for files ending with -store.js
and -substore.js
. This should be edited to match the projects naming conventions.
Then in main.js
(example with Vuex):
// Import plugin;// Normal imports;;; // Get new importer instanceconst importer = contextHmr; // Import all modules and get `module.default` from each module// Edit moduleKey value as necessary, this example imports from modules using:// `export default { state, getters, actions, mutations };`const modules = importer; // Framework setup using the modulesconst store = modules ; // Setup HMR with a callbackimporter; // Create new vue instance like normal el: '#app' store ;
Read more
License
MIT