配置

默认情况下,webpack 不会要求您使用配置文件。但是,它会假设您的项目入口点是 src/index.js,并将结果输出到 dist/main.js 中,该结果已缩小并针对生产进行了优化。

通常,您的项目需要扩展此功能,为此,您可以在根文件夹中创建一个webpack.config.js文件,webpack 将自动使用它。

所有可用的配置选项都在下面列出。

使用不同的配置文件

如果出于某种原因,您想根据特定情况使用不同的配置文件,您可以通过使用--config标志在命令行中更改它。

package.json

"scripts": {
  "build": "webpack --config prod.config.js"
}

设置一个新的 webpack 项目

Webpack 拥有大量的选项,可能会让您感到不知所措,请利用webpack-cli 的init命令,它可以快速为您的项目需求生成 webpack 配置文件,它会在创建配置文件之前向您提出一些问题。

npx webpack init

如果项目中或全局范围内尚未安装@webpack-cli/generators,npx 可能会提示您安装它。根据您在配置生成过程中做出的选择,您可能还会在项目中安装其他软件包。

$ npx webpack init

[webpack-cli] For using this command you need to install: '@webpack-cli/generators' package.
[webpack-cli] Would you like to install '@webpack-cli/generators' package? (That will run 'npm install -D @webpack-cli/generators') (Y/n)
devDependencies:
+ @webpack-cli/generators 2.5.0
? Which of the following JS solutions do you want to use? ES6
? Do you want to use webpack-dev-server? Yes
? Do you want to simplify the creation of HTML files for your bundle? Yes
? Do you want to add PWA support? No
? Which of the following CSS solutions do you want to use? CSS only
? Will you be using PostCSS in your project? Yes
? Do you want to extract CSS for every file? Only for Production
? Do you like to install prettier to format generated configuration? Yes
? Pick a package manager: pnpm
[webpack-cli] ℹ INFO  Initialising project...

devDependencies:
+ @babel/core 7.19.3
+ @babel/preset-env 7.19.4
+ autoprefixer 10.4.12
+ babel-loader 8.2.5
+ css-loader 6.7.1
+ html-webpack-plugin 5.5.0
+ mini-css-extract-plugin 2.6.1
+ postcss 8.4.17
+ postcss-loader 7.0.1
+ prettier 2.7.1
+ style-loader 3.3.1
+ webpack-dev-server 4.11.1
[webpack-cli] Project has been initialised with webpack!

18 位贡献者

sokraskipjackgrgurbondzsriccterinjokesmattcekbariotissterlingvixjeremenichellidasarianudeeplukasgeiterEugeneHlushkobigdawggianshumanvtextbookcoly010chenxsan