阅读(1886) (0)

前言

2023-05-17 16:23:54 更新

webpack 开箱即用,可以无需使用任何配置文件。然而,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 可能会提示你安装。根据你在配置生成过程中的选择,你也可能会安装额外的 package 到你的项目中。

$ 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!