Search code examples
webpackvue.jswebpack-hmr

Include importable modules from outside project folder for webpack HMR Vue.js


I have a project structure like:

.
+-- Common
|   +-- MyCommonVueComponent.Vue
+-- MainProject
|   +-- webpack.config.js
|   +-- package.json
|   +-- node_modules
|   +-- src

When I a build from the console webpack does not complain as it seemingly has a correct path to the node_modules folder for components imported from Common into MainProject. When I attempt to debug the Vue.js app in the browser I get the following error:

../Common/MyCommonVueComponent.Vue
Module not found: Error: Can't resolve 'vue-hot-reload-api' in 'D:\Projects\Cb\CommonVue'

I've added:

resolveLoader: {
        modules: [path.resolve(__dirname, './node_modules')],
    },

And that did seem to resolve path issues when running webpack in the console but not when debugging in the browser. Any help is appreciated. Hopefully someone who has setup a similar project structure can shed some light!


Solution

    • Vue-cli: v3.11.0
    • webpack: v4.40.2
    • babel: 7.6.0
    • node: v10.16.3

    I just ran into a similar situation tonight where I wanted to move out a few custom libraries into an external shared lib directory for agile development and mocked testing. I just started learning the Vue/webpack ecosystem about two weeks ago, and I can definitely say it's been an adventure with webpack being a daunting beast in figuring out all the mystical knobs and buttons that have to be aligned just right.

    ./devel  (webpack alias: TTlib)
    +-- lib
    |   +-- widget.js
    |   +-- frobinator.js
    |   +-- suckolux3000.js
    +-- share (suckolux3000.js taps into this directory)
    |   +-- imgs
    |   +-- icons
    |   |   +-- img
    |   |   +-- svg
    +-- MainProject
    |   +-- vue.config.js
    |   +-- package.json
    |   +-- node_modules
    |   +-- src
    +-- TestProject
    |   +-- vue.config.js
    |   +-- package.json
    |   +-- node_modules
    |   +-- src
    

    My concern was making sure that webpack HMR would work, and I can say you were close, but did not go far enough. Fortunately the fix was pretty simple.

    Here are my vue.config.js additions:

    module.exports = {
      configureWebpack: {
        resolve: {
          alias: {
            'TTlib': '/devel/lib'
          },
          modules: ['/devel/lib']
        },
        resolveLoader: {
          modules: ['/devel/lib']
        }
      }
    };
    

    Now from within any of my *Project components, I can just use:

    import frobinator from 'TTlib/frobinator'
    

    Now if I edit any of the project or (external) lib files, webpack HMR will kick in and refresh the running 'yarn serve' daemon and emit the changes I've made.

    Hope that helps!