Part 2: Transpile your code using Webpack
Overviewโ
- As you may notice in the
index.html
file, we're importing 2 javascript filesindex.js
androck_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.js
is able to use theRockPaperScissors
class fromrock_paper_scissors.js
because 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
webpack
command 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.js
and export theRockPaperScissors
class using theexport
keyword.
rock_paper_scissors.js
- class RockPaperScissors {
+ export class RockPaperScissors {
constructor(username) {
this.username = username;
}
...
- Go to
index.js
and import theRockPaperScissors
class using theimport
keyword.
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.js
and 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 webpack
to compile the code.- a new file named
main.js
will be created in thedist
folder.
- a new file named
- We can now replace the 2 script imports in
index.html
withmain.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.