webpack

最后更新: 2019-11-07 22:19:14 阅读: 26次

1、安装

(npm开发模式安装,并行安装webpack和webpack-cli(webpack四之后和webpack-cli已经分离开来,需分别安装))


npm install webpack webpack-cli  --save-dev
yarn 安装



yarn add webpack webpack-cli -D

2、使用webpack的两种方式


1)局部使用

(node_modules目录下的bin)


./node_modules/.bin/webpack ……(如 --version)
 npm 5之后适用(推荐)



npx webpack --version

在package.json中的scripts 加入build:"webpack",便可在命令行中直接执行npm run build进行webpack打包

{
  "name": "webpack-test",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "autoprefixer": "^9.7.1",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.2.0",
    "ejs-loader": "^0.3.5",
    "file-loader": "^4.2.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "image-webpack-loader": "^6.0.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9"
  }
}


2)全局使用(全局安装webpack)



npm install webpack webpack-cli -g
yarn global add webpack webpack-cli


3、watch进行监听文件变化

(每次webpack打包都很慢),在package.json的script配置watch,然后在命令行输入:npm run watch进行监听


 {
   "scripts": {
       "test": "echo "Error: no test specified" && exit 1",
       "build": "webpack",
       "watch":"webpack --watch"
    }
}
这种方式可以进行热的编译,但不能实现热的刷新,修改的内容不能直接显示,需要刷新才出现


2) 模块热替换

webpack控制浏览器,进行刷新操作,webpack-dev-server 支持 hot 模式,在试图重新加载整个页面之前,热模式会尝试使用 HMR 来更新

使用:1、安装 webpack-dev-server 

npm install  webpack-dev-server  --save-dev
//或者
yarn add webpack-dev-server -D
2、在package.json中配置script加入hot为webpack-dev-server

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack",
    "watch":"webpack --watch",
     "hot":"webpack-dev-server"
  },
3、在webpa.config.js中配置,增加devSever属性,开启热模块更替

 devServer:{
        hot:true
    },

同时引入webpack包,new webpack的热模块插件

 const webpack = require('webpack');
……………………
 plugins:[
        new htmlwebpackplugin({
            filename:'index.html',
            template:'index.html',
            inject:'body',
            title:'this is a',
        }),
        new webpack.HotModuleReplacementPlugin()
    ]
4、最后输入命令行npm run hot进行进行热模块更替