(二)Webpack 配置文件

Posted by ARTROY on 2019-08-03

Webpack 默认配置文件 webpack.config.js,不创建会使用默认的。

一、重置webpack.config.js
在根目录下创建 webpack.config.js

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

module.exports = {
mode: 'production', // production || development
// 打包文件
// entry: {
// main: './index.js'
// },
entry: './index.js', // 简写
// 打包好的文件放置
output: {
filename: 'bundle.js', // 重命名打包后的文件
// 放置路径
/**
* 打包好的文件放置路径
* __dirname 是指当前webpack.config.js所在的当前目录
* 与bundle结合:即在当前目录下生成bundle文件夹
*/
path: path.resolve(__dirname, 'bundle')
}
}

执行 npx webpack即可。打包后的文件目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
|-- bundle
|-- bundle.js
|-- index.html
|-- index.js
|-- node_modules
|-- package.json
|-- webpack.config.js
|-- js
|-- header.js
|-- content.js
|-- footer.js
|-- img
|-- abc.jpg
|-- abc.png

二、简化打包文件代码
修改 package.json 文件下的 scripts。即:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"name": "webpack",
"version": "1.0.0",
"description": "webpack",
"main": "index.js",
/** 修改前 **/
// "scripts": {
// "test": "echo \"Error: no test specified\" && exit 1"
// },
/** 修改后 **/
"scripts": {
"bundle": "webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6"
}
}

修改后执行 npm run bundle即可打包, 打包后记得修改 index.html 里面链接 js 的文件。

打包文件出现如下提示,则可以在 webpack.config.js 文件下添加 mode: 'production' 或者 mode: 'development'
提示



支付宝打赏 微信打赏

欣赏此文,打赏一下



-->