B
B
bjorn-mozyakin2019-10-14 15:43:11
JavaScript
bjorn-mozyakin, 2019-10-14 15:43:11

How to build different js bundles using Common Components (ES6 modules) if these modules have external dependencies?

I don’t understand how to use common es6 modules (from my own module library, for example) when you need to build 2 different js bundles from them (for example, for the desktop and mobile versions of the site). In a situation where these shared modules have external dependencies .
Let's say we need to implement a button repainting in blue when clicking on it.
The structure of the modules in a simplified form is as follows:

// ===== mainMobile.js - главная точка входа

import Button from './button.js';

let colorMain = 'blue';
new Button(document.querySelector('.button'));

export { colorMain }

// ===== button.js

import { colorMain } from './mainMobile.js';

export default class Button {
  constructor(elem) {
    this.elem = elem;
    this.elem.addEventListener('click', () => { this.paint(); })	
  }

  paint() {
    this.elem.classList.add(`button_${colorMain}`);
  }
}

I specify the webpack entry point - mainMobile.js - the bundle builds fine.
Now let's say we need to build another bundle (for desktop). Desktop has minor differences (for example, when a button is clicked, it turns green instead of blue).
I create a mainDesktop.js file that is similar to mainMobile.js. For a desktop button, I want to use the already existing button.js module.
// ===== mainDesktop.js - главная точка входа

import Button from './button.js';

let colorMain = 'green';
new Button(document.querySelector('.button'));

export { colorMain }

And I'm running into a problem . In the general button.js module, I need to import the colorMain variable, but from where? In the assembly for mobile, it must be imported from mainMobile.js, in the assembly for desktop - from mainDesktop.js.
How to differentiate? At the js code level or at the webpack build config level? No understanding
First, I assume that dynamic imports can somehow help , but I can't figure out how to use them.
Secondly, I assume that my initial approach may be wrong (when I basically export something to modules from the main entry point). But what's the alternative?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question