webpack入门(3): 使用配置文件webpack.config.js及多入口的配置

webpack入门(3): 使用配置文件webpack.config.js及多入口的配置

如果想修改webpack的默认入口,出口,使用的插件,loader时,可以通过控制台的webpack指令传入参数

1
webpack --entry xxxx

来定义入口文件

但是更多的做法是创建一个webpack.config.js文件,利用这个文件对进行相关的配置

下面介绍使用webpack.config.js的基本配置以及多

使用webpack.config.js

创建方式

  • 可以手动新建文件,
  • 也可以使用npx webpack init指令初始化配置文件

使用npx webpack init命令

在输入指令后根据提示创建配置文件

1
2
3
4
5
6
7
8
9
10
11
npx webpack init

i INFO For more information and a detailed description of each question, have a look at: https://github.com/webpack/webpack-cli/blob/master/INIT.md
i INFO Alternatively, run "webpack(-cli) --help" for usage info

? Will your application have multiple bundles? No
? Which will be your application entry point? src/index
? In which folder do you want to store your generated bundles? dist
? Will you use one of the below JS solutions? ES6
? Will you use one of the below CSS solutions? CSS
? Overwrite src\index.js? overwrite

手动创建webpack.config.js

在项目根目录创建webpack.config.js

1564065479810

编辑文件

webpack.config.js

使用module.exports暴露模块

  • entry 定义入口文件

  • output 定义输出文件

  • plugins 使用的插件

  • module 使用的loader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const path = require('path');

module.exports = {
// 使用开发者模式
mode: 'development',
// 定义入口
entry: './src/index.js',

// 定义输出文件
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},

/*
// 定义插件
plugins: [new webpack.ProgressPlugin(), new HtmlWebpackPlugin()],
// 定义loader
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
*/
};

配置好之后运行npx webpack

输出

1564066523460

配置多个入口

入口

这里使用3个js文件

1564067016774

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
module.exports = {
// 使用对象语法定义3个入口文件
entry: {
pageOne: './src/index1.js',
pageTwo: './src/index2.js',
pageThree: './src/index3.js'
},
// 分别输出3个js文件,[name]表示对应的文件名
output: {
filename: '[name].js',
path: __dirname + '/dist'
}
};

运行npx webpack

输出

1564067057602

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×