一、安装WebPack

  • 全局安装

npm install webpack@3.6.0 -g

  • 局部安装 —save-dev 添加开发环境依赖

npm install webpack@3.6.0 --save-dev

  • 查看版本

webpack --version

  • 卸载webpack

npm uninstall webpack

二、配置webpack.config.js

  1. //1.导入node的path包获取绝对路径,需要使用npm init初始化node包
  2. const path = require('path')
  3. //2.配置webpack的入口和出口
  4. module.exports = {
  5. mode:'development',//打包模式 默认为 production(生产环境带压缩)
  6. entry: './src/main.js',//入口文件
  7. output:{
  8. path: path.resolve(__dirname, 'dist'),//动态获取打包后的文件路径,path.resolve拼接路径
  9. filename: 'bundle.js'//打包后的文件名 bundle[hash:4].js可设置哈希值打包出不同文件版本
  10. },
  11. devServer: { //开发时服务器配置
  12. port: 2555,
  13. progress: true,
  14. contentBase: './dist'
  15. },
  16. plugins: [
  17. new htmlWebpackPlugin({
  18. template: './view/index.html',
  19. filename: 'index.html'
  20. })
  21. ]
  22. }

三、设置package.json映射webpack命令

npm run build 时默认会在本地项目查找,然后在查找全局项目

  1. {
  2. "name": "webpack1",
  3. "version": "1.0.0",
  4. "description": "",
  5. "private": true,
  6. // "main": "index.js",
  7. "scripts": {
  8. "test": "echo \"Error: no test specified\" && exit 1",
  9. "build": "webpack" //运行webpack命令
  10. "dev" : "webpack --config webpack.myconfig.js", //自定义配置文件名称
  11. "server" : "webpack-dev-server" //本地服务器
  12. },
  13. "author": "",
  14. "license": "ISC",
  15. "dependencies": {
  16. }
  17. }

"private": true 确保我们安装包是私有的(private),并且移除 main 入口。这可以防止意外发布你的代码。
"build": "webpack" 运行webpack命令
"dev" : "webpack --config webpack.myconfig.js" 自定义配置文件名称