webpack/vue/nuxt - Map import if file exists (overwrite)

Viewed 28

In my current project I am trying to implement the following:

Let's assume the following file structure:

/src/
/src/components/MyComponent.vue
/src/overwrites/components/MyComponent.vue

(in any *.vue file): import MyComponent from '@/components/MyComponent.vue'.

This import should, if the same file exists in the parallel existing directory "overwrites", import it instead of the one from /src/components/.

To benefit from hot reloading etc, I want to solve this via webpack.

However, how to extend the vue-loader or get in front of it I haven't figured out.

2 Answers

You can use require.context to crawl directory for components without a webpack or vue-loader involved.

For instance you have structure:

.src
+-- components
|   +-- MyComponent.vue
+-- overwrites
|  +-- components
|  |   +-- MyComponent.vue

You will put index.js file in every components folder with content:

const requireModule = require.context('./', false, /\.vue$/)
requireModule.keys().forEach(fileName => {
    if (fileName === './index.js') return;
    const moduleName = pascalCase(
        fileName.replace(/(\.\/|\.vue)/g, '')
    );
    components[moduleName] = requireModule(fileName)
});
export default components;

Then you will be able to import those index.js files in root component file like:

import components from './components/index.js';
export default {
    components: components,
    // ...
}

It will load all vue files from components directory. It will solve the issue of hot reloading.

Though, you will have to manage loading of duplicated components on your own, probably with Object.assing like:

import components from './components/index.js';
import {components as overwrites} from './overwrites/components/index.js';
export default {
    components: Object.assign({}, components, overwrites),
    // ...
}

Duplicated components will be substituted.

Related