I have multiple entries like in webpack docs
module.exports = {
entry: {
pageOne: './src/pageOne/index.js',
pageTwo: './src/pageTwo/index.js',
pageThree: './src/pageThree/index.js'
}
};
let's say every of these files (index.js) is the same and only thing that change is other routes import.
I would create one file to keep DRY principle but I would need to pass something to actually know which router I want to import.
For example pageOne/index.js is
import Vue from 'vue'
import axios from 'axios'
import App from '../App'
import { store } from '../store';
import VueProgressBar from 'vue-progressbar'
import Router from '../routers/router';
import interceptor from '../../config/httpInterceptor.js';
console.log('in main', window.location.href)
const routerInstance = new Router('main');
routerInstance.createRouter()
.then(router => {
interceptor();
if (!process.env.IS_WEB) Vue.use(require('vue-electron'));
Vue.http = Vue.prototype.$http = axios;
Vue.config.productionTip = false;
Vue.use(VueProgressBar, {
color: 'rgb(255, 85, 0)', failedColor: 'red', thickness: '5px'
});
new Vue({
components: { App },
router,
store,
template: '<App/>'
}).$mount('#app');
});
and in pageTwo/index.js only line that change is from
const routerInstance = new Router('main');
to
const routerInstance = new Router('second');
so it's bad to have three same js files where only one line is changing but I don't know how to refactor it so it's reusable. I would need to pass to file information about which page is being loaded for example it would be something like this
module.exports = {
entry: {
pageOne: './src/pageOne/index.js?page=main',
but now when in index.js I log
console.log('in main', window.location.href)
it is
http://localhost:9080/#/
So I'm not able to require different router basing on this. I need some other solution.
Edit
@Daniel Lizik in comment section suggested to use environment variable. He also said to use webpack config in order to set it. Considering that I would refactor my entry object to following:
module.exports = {
entry: {
pageOne: './src/index.js',
pageTwo: './src/index.js',
pageThree: './src/index.js'
}
};
I would need to configure webpack somehow to set environment variable right after webpack imported file.
Webpack probably loop over this object and import files. Right after it read this line
pageOne: './src/index.js',
I would need to set some env variable to 'pageOne' so when index.js is executed it can check this variable and import correct router.
However I have no idea how I could achieve that.