go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Webpack In Action
 
Subject: Webpack In Action
Author: WebSpider
In response to: How to config Webpack
Posted on: 04/22/2021 11:51:59 PM

c:\tmp\webpack\hello-w-webpack>npm run build


> hello-w-webpack@1.0.0 build C:\tmp\webpack\hello-w-webpack
> webpack -w

asset bundle.js 4.58 KiB [compared for emit] (name: main)
runtime modules 670 bytes 3 modules
cacheable modules 471 bytes
  ./src/main.js 147 bytes [built] [code generated]
  ./src/game.js 324 bytes [built] [code generated]
webpack 5.35.0 compiled successfully in 103 ms


The packed file 'bundle.js' should be shown under 'public'
[+] hello-w-webpack
 |.. [+] src
 |....... game.js
 |....... main.js
 |.. [+] public
 |....... index.html
 |....... bundle.js
 |....... style.css
 |.. package.json
 |.. webpack.config.js


 

> On 04/22/2021 11:42:40 PM WebSpider wrote:

[+] hello-w-webpack
 |.. [+] src
 |....... game.js
 |....... main.js
 |.. [+] public
 |....... index.html
 |....... style.css
 |.. package.json
 |.. webpack.config.js


webpack.config.js
const path = require('path');

module.exports = {
  mode: "development", // could be "production" as well
  entry: './src/main.js', // the starting point for our program
  output: {
    path: path.resolve(__dirname, 'public'), // the absolute path for the directory where we want the output to be placed
    filename: 'bundle.js' // the name of the file that will contain our output - we could name this whatever we want, but bundle.js is typical
  }
};


package.json
{
  "name": "hello-w-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -w"  // to watch for files changes
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.35.0",
    "webpack-cli": "^4.6.0"
  }
}


game.js:
 let numTimesClicked = 0;

  function win() {
    alert('You win!');
    reset();
  }

  function reset() {
    numTimesClicked = 0;
  }

  function click() {
	  
    numTimesClicked++;
	
    console.log(`You've been clicked!`);
	
    if (numTimesClicked === 3) 
		win();
  }

export default click; 



main.js
import click from './game' 
const button = document.getElementById('button');

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


index.html
<!DOCTYPE html>
<html lang="en">
	<head>
	    <script src="./bundle.js"></script>	  
	</head>
	
	<body>

	  <button id="button">Click Me!</button>
	  
	</body>
</html>





References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.