大多数项目会需要很复杂的设置,需要使用配置文件。
1.添加配置文件
- 项目根目录下创建 config 文件夹
- 创建 webpack.config.js 文件,并添加内容
const path = require('path');
module.exports = {
// 指定打包模式:development、production
mode:"development",
// entry 对象是用于 webpack 查找启动并构建 bundle。其上下文是入口文件所处的目录的绝对路径的字符串。
entry: './src/index.js',
// 输出文件配置
output: {
// 文件名称
filename: 'main.js',
// 文件路径
path: path.resolve(process.cwd(), 'dist')
}
};
2.通过配置文件打包
执行以下指令
npx webpack --config ./config/webpack.config.js
等待打包完成后,打开 index.html 文件能显示 Hello webpack ! 。
如果 webpack.config.js 存在,则 webpack 命令将默认选择使用它。这里使用 --config 选项表明,可以传递任何名称的配置文件。这对于需要拆分成多个文件的复杂配置是非常有用。
3. 通过 NPM 脚本打包
修改 package.json 文件,添加 scripts
{
"name": "vue2-webpack4-project",
"version": "1.0.0",
"private": true,
"main": "index.js",
"repository": "https://github.com/hao-kuai/vue2-webpack4-project.git",
"author": "https://github.com/hao-kuai",
"license": "MIT",
"scripts": {
"build": "webpack --config ./config/webpack.config.js"
},
"devDependencies": {
"webpack": "4.46.0",
"webpack-cli": "^4.10.0"
}
}
然后执行
npm run build
<!--或-->
yarn run build
等待打包完成后,打开 index.html 文件能显示 Hello webpack !