Detailed use of Webpack

Webpack is a static module bundler for modern JavaScript applications. This article will detail how to use Webpack and provide code examples. To keep things short, we'll briefly introduce Webpack's core concepts and capabilities.

1. Core concepts

Entry: The starting point of the application.
Output: the output location of the packaged resource.
loader: Converts non-JavaScript files into modules.
Plugins (plugins): perform a wider range of tasks, such as optimization, compression, etc.

2. Installation and configuration

1. Installation

First, make sure you have Node.js installed on your system. Install Webpack and Webpack CLI with the following commands:

npm install --save-dev webpack webpack-cli
2. Configuration

In the project root directory, create a configuration file called webpack.config.js. Here is a simple configuration example:

const path = require('path');

module.exports = {
    
    
  entry: './src/index.js', // 入口文件
  output: {
    
    
    filename: 'bundle.js', // 输出文件名
    path: path.resolve(__dirname, 'dist') // 输出目录
  }
};

3. Loaders and plugins

1. Loader

Loaders are used to convert non-JavaScript files into modules. Here are some examples of commonly used loaders:

(1) Style loader
Install style-loader and css-loader:

npm install --save-dev style-loader css-loader

Configuration:

module.exports = {
    
    
  // ...
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

(2) File loader
Install file-loader:

npm install --save-dev file-loader

Configuration:

module.exports = {
    
    
  // ...
  module: {
    
    
    rules: [
      {
    
    
        test: /\.(png|svg|jpg|jpeg|gif)$/,
        use: ['file-loader']
      }
    ]
  }
};
2. Plugins

Plugins can perform a wider range of tasks such as optimization, compression, etc. Here are some examples of commonly used plugins:

(1) HtmlWebpackPlugin
installs html-webpack-plugin:

npm install --save-dev html-webpack-plugin

Configuration:

const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    
    
  // ...
  plugins: [
    new HtmlWebpackPlugin({
    
    
      title: 'My App',
      template: './src/index.html'
    })
  ]
};

(2) CleanWebpackPlugin
安装 clean-webpack-plugin:

npm install --save-dev clean-webpack-plugin

Configuration:

const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
    
    
  // ...
  plugins: [
    new CleanWebpackPlugin()
  ]
};

4. Development and production environment

1. Mode

Webpack supports two modes: development and production. Development mode does not perform code compression and optimization, while production mode does code compression and optimization. Set the mode in the webpack.config.js file:

module.exports = {
    
    
  // ...
  mode: 'development' // 或 'production'
};
2. Development server

Install webpack-dev-server:

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

Configuration:

module.exports = {
    
    
  // ...
  devServer: {
    
    
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000
  }
};

5. Example project

Here is a simple Webpack example project:

  1. Create directory structure:
my-app/
|-- src/
|   |-- index.html
|   |-- index.js
|   |-- styles.css
|   |-- image.png
|-- package.json
|-- webpack.config.js
  1. Populate the files in the src directory:
  • index.html
<!DOCTYPE html>
 <html> 
 	<head> 
		 <meta charset="utf-8" />
 		 <title>My App</title>
   </head>
   <body> 
    	<div id="app"></div> 
   		<script src="bundle.js"></script> 
   </body> 
</html> 
  • index.js
import './styles.css';
import imgSrc from './image.png';

const app = document.getElementById('app');
app.innerHTML = `
  <h1>Hello, Webpack!</h1>
  <img src="${
      
      imgSrc}" alt="Webpack Logo" />
`;
  • styles.css
body {
    
    
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
    
    
  color: #2c3e50;
}

img {
    
    
  width: 150px;
  height: 150px;
}
  1. Configure loaders and plugins in webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    
    
  entry: './src/index.js',
  output: {
    
    
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  mode: 'development',
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
    
    
        test: /\.(png|svg|jpg|jpeg|gif)$/,
        use: ['file-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html',
    }),
    new CleanWebpackPlugin(),
  ],
  devServer: {
    
    
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000,
  },
};
  1. Add startup script in package.json:
{
    
    
  // ...
  "scripts": {
    
    
    "start": "webpack serve",
    "build": "webpack"
  },
  // ...
}
  1. Run the project:
npm start

Visit http://localhost:9000 to see the example project. Use npm run build to package the project.

Summarize

Through this article, you should have mastered the basic usage of Webpack. In actual projects, you may need to further configure Webpack according to your needs. For more information and advanced configuration, check out the official Webpack documentation .

Guess you like

Origin blog.csdn.net/ZTAHNG/article/details/131223393