W
W
wakenbyWork2021-09-30 19:38:39
gulp.js
wakenbyWork, 2021-09-30 19:38:39

How to work modularly in js with webpack?

I build scss + pug via gulp, and for js I use webpack.

And this is how I write modules in modules:

hamburger.js - a separate module that is responsible for hiding and showing the mobile menu

const hamburger = document.querySelector('.hamburger')
const mobileMenu = document.querySelector('.mobile-menu')
const header = document.querySelector('.header')

start()
function start () {
  if (!hamburger || !mobileMenu) return

  hamburger.addEventListener('click', onClick)
}

function onClick () {
  setSizeMobileMenu()

  hamburger.classList.toggle('is-active')
  mobileMenu.classList.toggle('mobile-menu--close')

  if (hamburger.classList.contains('is-active')) {
    hiddenScroll()
  } else {
    showScroll()
  }
}

function setSizeMobileMenu () {
  const { bottom } = header.getBoundingClientRect()

  mobileMenu.style.top = `${bottom}px`
  mobileMenu.style.height = `calc(100vh - ${bottom}px)`
}

function hiddenScroll () {
  document.body.style.overflow = 'hidden'
}

function showScroll () {
  document.body.style.overflow = ''
}

(I write the start function so that there are no errors on pages where there are no necessary dom elements). Is it possible to refuse the start function?

After I import it like this in the main js file:

main.js - input file for webpack
import '%modules%/hamburger/hamburger'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Kulakov, 2021-09-30
@ivankprod

./modules/module.js

export function some() {
  console.log('asd');
}

export default { some }

main.js
import './modules/module.js';
some();

// или
import MyModule from './modules/module.js';
MyModule.some();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question