I'm going to assume we have a directory called 'myApp' and an index.html
cd myApp
npm init -y
This will create a package.json file.
Within package.json, add some text to the "description" field to avoid a warning at the next stage.
If you're not going to use git at this stage also within package.json, add the line "private": true,
Again this is to avoid warnings.
Now we're ready to take node modules.
npm install webpack webpack-cli --save-dev
Now we create a file for configuring webpack.
touch webpack.config.js
Now let's create a directory structure for our source.
mkdir src
cd src
mkdir js
mkdir css
cd js
touch output.js
Now let's add some code to output.js and save.
console.log('Hello world!');
Now let's go back to the myApp directory.
cd ../..
Now we can edit the webpack.config.js file.
Add the following content to webpack.config.js and save.
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/js/output.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
}
You can see from the code above a number of things:
- A 'path' constant to be used to establish where to get files from.
- A module.exports object.
- The mode in which we're working.
- 'entry' is the start location that webpack will look to find the things it need to bundle.
- 'output' is the location of the bundle.
So our HTML file, index.html will look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webpack</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
Now it's time to run webpack
From the command line, and in the 'myApp' directory type:
webpack
The result should be a directory called 'dist', which contains a file called bundle.js.
When loading the page, if we look at the console. It should say 'Hello world!'.