Webpack is a module bundler for JavaScript applications. It is used to automate the process of bundling and combining files and assets (like JavaScript, HTML, CSS and even images). It also enables scope hoisting, module splitting, and the ability to handle static assets through loaders.
Webpack creates a graph that maps every module your project needs, then packages all of those modules into a small number of ‘bundles’ – often only one – to be loaded by the browser.
Here’s the basic usage of Webpack:
1. Installation: Install it via npm or yarn.
– nmp: `npm install —save-dev webpack` – yarn: `yarn add webpack —dev`1. Creating a Webpack Configuration File: The file is named `webpack.config.js`. This file processes the application’s source files and modules.
A sample of a webpack.config.js: \`\`\`javascript const path = require(‘path’); module.exports = { entry: ‘./src/index.js’, output: { filename: ‘main.js’, path: path.resolve(\_\_dirname, ‘dist’), }, }; \`\`\` Here, the entry point is ‘src/index.js’. So, all the Javascript files which are to be imported will be through this file. ‘dist/main.js’ is the file where the bundled output will be exported.1. Include your Script for bundling: Include your script in package.json file as below:
\`\`\`json “scripts”: { “build”: “webpack“ } \`\`\` You can run the script by typing npm run build or yarn build to bundle your application.1. Loaders: Webpack allows adding loaders for other types of files like .css, .scss, .jpg, .png etc.
1. Plugins: Webpack also offers a wide variety of plugins for complex tasks like minifying JavaScript, CSS, support for Hot Module Replacement etc.
Lastly, remember Webpack only runs on Node.js environment, so you need to have Node.js and npm installed on your machine.