Reading:
Webpack Project Setup

Webpack Project Setup

Metamug
Webpack Project Setup

Installing webpack

npm init
npm install --save-dev webpack
npm install --save-dev webpack-cli

Project Structure

create a src and test folder and manually create webpack.config.js

index.js

Create index.js in src folder

const user = require("./user")

user.js

//your code here

Project Configuration

Inside package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "devDependencies": {
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0"
  }

webpack.config.js

var path = require('path');

module.exports = {
  resolve: {
  fallback: {
    "fs": false,
    "path": false
    },
  }
};

Run Command

npm run dev
npm run build

Webpack Dev server

Install latest nodejs before installing webpack-dev-server

https://stackoverflow.com/questions/10075990/upgrading-node-js-to-latest-version?answertab=trending#tab-top

Webpack dev server is useful in hot deployment.

npm install --save-dev webpack-dev-server

Change the package.json file to  add following command.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "npm webpack serve",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "devDependencies": {
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server":"^4.0.0"
  }

In webpack.config.js,

devServer: {
  static: {
    directory: path.join(__dirname, 'public'),
  },
  compress: true,
  port: 9000,
}

If your files lie in the root directory.

Inside your 

https://webpack.js.org/configuration/dev-server/

Hot deployment not working

Once webpack-dev-server builds the bundle.js file it places it into dist folder. Inside the index.html, do not use the dist folder bundle.js, webpack updates the bundle.js in the directly specified by devserver.

// index.html
<script src="bundle.js"></script>      // works
<script src="dist/bundle.js"></script> // doesn't work!

https://stackoverflow.com/questions/39066298/webpack-dev-server-hot-reload-not-working

Source Code Management

Also do not forget to add gitignore for webpack. 

https://github.com/webpack/webpack/blob/main/.gitignore



Icon For Arrow-up
Comments

Post a comment