---
# System prepended metadata

title: Modules + Webpack

---

# Modules + Webpack
### `main.js`

```jsx
// main.js
const button = document.getElementById('button');

button.addEventListener('click', function(e) {
  click();
})
```

### `game.js`

```jsx
let numTimesClicked = 0;

let prizes = ['Zoyru Plush', 'Pikachu Plush', 'Reebok Pumps', 'Lifetime Supply of 25c Barrel Drinks', 'Lifetime Supply of Dunkaroos']

let prizeList = document.getElementById('prizes-list')

function win() {
  alert(`You win!`);
  prizes.forEach(prize => {
    let node = document.createElement('li')
    node.innerHTML = prize
    prizeList.append(node)
  })
  reset();
}

function reset() {
  numTimesClicked = 0;
}

function click() {
  numTimesClicked++;
  console.log(numTimesClicked)
  if( numTimesClicked === 10 ) win();
}
```

### Add scripts to HTML

```jsx
<script type="text/javascript" src="src/main.js"></script>
<script type="text/javascript" src="src/game.js"></script>
```

## What is wrong with above?

Everything is in the global scope. I have access to  everything. 

## `module.exports` and `require` don't work here. Why? Because we are on the frontend.

## A better way to above and being able to use `module.exports`: Using `webpack`

Webpack is a module bundler. It packages many different JavaScript modules (files) into a JavaScript file to be executed in the browser.

### Install `webpack`

```jsx
npm i webpack
npm i webpack-cli
```

### Comment out these lines in `index.html`

```html
<script type="text/javascript" src="src/main.js"></script>
<script type="text/javascript" src="src/game.js"></script>
```

### Create a `webpack.config.js`

```jsx
module.exports = {
    mode: "development",
    entry: "./src/main.js",
    output: {
      path: __dirname + "/public",
      filename: "bundle.js"
    }
}
```

### Create a script in `package.json`

```jsx
"build": "webpack -w"
```

### Include `bundle.js` in the HTML file

```jsx
<script type="text/javascript" src="public/bundle.js" defer></script>
```

### Now we can try to do `module.exports` and `require`

### Export `click` function from `game.js`

```jsx
//module.exports = click;
export click
```

### `require` `click` function in `main.js`

```jsx
//const click = require('./game');
import click from './game'
```