跳到主要内容

概念

Entry 入口

Entry 告诉 webpack 应该使用哪个模块,来作为构建其内部依赖图的开始:

webpack.config.js
module.exports = {
entry: './path/to/my/entry/file.js',
};

Output 输出

Output 告诉 webpack 在哪里输出它所创建的 bundle ,以及如何命名这些文件。主要输出文件的默认值是 ./dist/main.js,其他生成文件默认放置在 ./dist 文件夹中:

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

module.exports = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'), // `__dirname` 为当前模块目录名
filename: 'my-first-webpack.bundle.js',
},
};

Loader

Webpack 自身只能理解 JS 和 JSON 文件。Loader 让 webpack 能够去处理其他类型的文件,并将它们转换为有效模块:

webpack.config.js
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js',
},
module: {
// 在遇到 '.txt' 文件时,使用 `raw-loader` 转为模块
rules: [{ test: /\.txt$/, use: 'raw-loader' }],
},
};

Plugin 插件

Plugin 用于执行打包优化,资源管理,注入环境变量等范围更广的任务:

webpack.config.js
const webpack = require('webpack'); // webpack 自带许多插件
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
module: {
rules: [{ test: /\.txt$/, use: 'raw-loader' }],
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
};

Mode 模式

Mode 可以为不同环境设置相应的优化行为:

webpack.config.js
module.exports = {
mode: 'production', // 还有 `development`、`none` 模式
};