Testing with Webpack
1. Create a new folder called webpack.
2. cd into a new folder.
3. Verify both node.js and npm is installed.
4. Run the command npm init to initialize the dir.
(Select enter for each of the default options)
This should create a new package.json file in your folder which looks something like this:
{
"name": "webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
5. In root dir create a new folder called scripts and in that folder create a new javascript sample file called App.js and add some simple code to add an alert:
alert("This is just a test")
6. Next you want to install Webpack and Webpack cli
npm install webpack webpack-cli --save-dev
7. In the root dir create a new file webpack.config.js
8. Add the following entry point to webpack.config.js:
module.exports = {
entry: './scripts/App.js'
}
9. Go to package.json file and create a new npm script:
"scripts": {
"dev": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
10. Go to the command line and run: npm run dev;
- This should create a folder called dist and a file called main.js.
11.
a. What if we want to name the file something else besides main.js?
b. What if we want to put it into a different folder?
c. What if we want Webpack to automatically generate the bundled file every time we make a change?
12. To do the above we need to edit the webpack.config.js with the following code:
const path = require('path')
module.exports = {
entry: './scripts/App.js',
output: {
filename: 'bundled.js',
path: path.resolve(__dirname, 'scripts')
},
mode: 'development'
}
13 Now run npm run dev again and you can see that the file is created in the root dir.
14 We can go to index.html in the browser and we see the alert.
15 If we go back and edit app.js and run npm run dev again we can see the file has changed.
16 Now if we want to have Webpack automatically pick up on the changes we add. We need to add the watch option to the bottom of the code like below and run npm dev again
const path = require('path')
module.exports = {
entry: './scripts/App.js',
output: {
filename: 'bundled.js',
path: path.resolve(__dirname, 'scripts')
},
mode: 'development',
watch: true
}