一、安装WebPack
- 全局安装
npm install webpack@3.6.0 -g
- 局部安装 —save-dev 添加开发环境依赖
npm install webpack@3.6.0 --save-dev
- 查看版本
webpack --version
- 卸载webpack
二、配置webpack.config.js
//1.导入node的path包获取绝对路径,需要使用npm init初始化node包const path = require('path')//2.配置webpack的入口和出口module.exports = {mode:'development',//打包模式 默认为 production(生产环境带压缩)entry: './src/main.js',//入口文件output:{path: path.resolve(__dirname, 'dist'),//动态获取打包后的文件路径,path.resolve拼接路径filename: 'bundle.js'//打包后的文件名 bundle[hash:4].js可设置哈希值打包出不同文件版本},devServer: { //开发时服务器配置port: 2555,progress: true,contentBase: './dist'},plugins: [new htmlWebpackPlugin({template: './view/index.html',filename: 'index.html'})]}
三、设置package.json映射webpack命令
npm run build 时默认会在本地项目查找,然后在查找全局项目
{"name": "webpack1","version": "1.0.0","description": "","private": true,// "main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","build": "webpack" //运行webpack命令"dev" : "webpack --config webpack.myconfig.js", //自定义配置文件名称"server" : "webpack-dev-server" //本地服务器},"author": "","license": "ISC","dependencies": {}}
"private": true 确保我们安装包是私有的(private),并且移除 main 入口。这可以防止意外发布你的代码。"build": "webpack" 运行webpack命令"dev" : "webpack --config webpack.myconfig.js" 自定义配置文件名称
