Part 2: Transpile your code using Webpack
Overviewโ
- As you may notice in the
index.htmlfile, we're importing 2 javascript filesindex.jsandrock_paper_scissors.js.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<script src="resources/scripts/rock_paper_scissors.js"></script>
<script src="resources/scripts/index.js"></script>
</body>
</html>
- In runtime,
index.jsis able to use theRockPaperScissorsclass fromrock_paper_scissors.jsbecause it's imported before it inindex.html. - This is not the best setup. As you lose of the IDE intellisense, and your IDE thinks that RockPaperScissors doesn't not exist.
- To fix this, we can use the
webpackcommand line tool. to modularize the code and import one file into the other. - Finally, we will only import a single script file into
index.html.
Installing Webpackโ
- Install Webpack from npm.
npm install webpack webpack-cli --save-dev
Modularize existing codeโ
- Go to
rock_paper_scissors.jsand export theRockPaperScissorsclass using theexportkeyword.
rock_paper_scissors.js
- class RockPaperScissors {
+ export class RockPaperScissors {
constructor(username) {
this.username = username;
}
...
- Go to
index.jsand import theRockPaperScissorsclass using theimportkeyword.
index.js
+ import { RockPaperScissors } from './rock_paper_scissors.js';
// Elements
const welcomeScreen = document.getElementById(`welcome-screen`);
const gameScreen = document.getElementById(`game-screen`);
Configuring Webpackโ
- Create a new file
webpack.config.jsand copy the following code into it.
webpack.config.js
const path = require('path');
module.exports = {
entry: './resources/scripts/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
}
};
danger
I purposely made an error in the above. You should debug when you run webpack to see what's wrong.
Running Webpackโ
- Run
npx webpackto compile the code.- a new file named
main.jswill be created in thedistfolder.
- a new file named
- We can now replace the 2 script imports in
index.htmlwithmain.js.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
-- <script src="resources/scripts/rock_paper_scissors.js"></script>
-- <script src="resources/scripts/index.js"></script>
++ <script src="dist/main.js"></script>
</body>
</html>
tip
As a side effect of actually importing and exporting the code, we no longer get the Eslint errors about that.