webpack入门实例步骤+使用webpack-dev-server实现热加载

1、基础项目启动

1)新建项目,执行npm init,生成package.json文件;
2)下载webpack,npm install webpack --save-dev,开发环境需要,用–save-dev安装到devDependencies中;
3)新建webpack.config.js文件

const path = require("path")

module.exports = {
  // 入口文件路径
  entry: path.resolve(__dirname, 'index'),
  output: {
    // 出口文件存放的位置 新建一个bundle文件夹
    path: path.resolve(__dirname, 'bundle'),
    // 文件名
    filename: 'webpack-bundle.js'
  },
  // 未设置时,启动报下面的错误
  mode: 'development'
}

webpack入门实例步骤+使用webpack-dev-server实现热加载_第1张图片
package.json文件

{
  "name": "two",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "author": "wsx",
  "license": "ISC",
  "devDependencies": {
    "install": "^0.13.0",
    "webpack": "^4.35.3",
    "webpack-cli": "^3.3.6",
    "webpack-dev-server": "^3.7.2"
  }
}

启动:npm run start
启动之后,会在文件目录下新建bundle文件夹,里面是打包的js文件。在index.html里引入js,打开html页面,就能看到在index.js文件里编写的内容
webpack入门实例步骤+使用webpack-dev-server实现热加载_第2张图片
启动项目到此完成。

2、实现热加载

1)需要监听index.js改变,可以在package文件里进行设置:
“start”: “webpack --watch --config webpack.config.js”
启动:npm run start
PS:在项目中,提交代码时,不能把watch给提交上去,一直watch,会把服务拖死的,注意!

2)webpack-dev-server可以做到热加载,依赖webpack-cli,安装需安装两。
同时需要安装HtmlWebpackPlugin,打包输出HTML

const path = require("path")
const webpack = require("webpack")

module.exports = {
  entry: path.resolve(__dirname, 'index'),
  output: {
    path: path.resolve(__dirname, 'bundle'),
    filename: 'webpack-bundle.js'
  },
  devServer: {
    inline: true, //实时刷新
    hot: true, // 模块热替换机制
    host: '0.0.0.0', //设置服务器的主机号,默认是localhost
    port: 9000,
    //本地服务器所加载的页面所在的目录
    contentBase: path.resolve(__dirname, 'bundle'), 
    compress: true,
    open: true // 打开浏览器,默认false
  },
  plugins: [
    new HtmlWebpackPlugin({ //打包输出HTML
      filename: './index.html',
      template: 'index.html'
    }),
    new webpack.HotModuleReplacementPlugin() // 热加载
  ],
  mode: 'development'
}
{
  "name": "two",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --watch --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --mode  development ", // 启动npm run dev
    "build": "webpack --mode production"
  },
  "author": "wsx",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "install": "^0.13.0",
    "webpack": "^4.35.3",
    "webpack-cli": "^3.3.6",
    "webpack-dev-server": "^3.7.2"
  }
}

index.html不需要再引用bundle.js,启动:npm run dev(根据package.json文件的配置来的)
webpack入门实例步骤+使用webpack-dev-server实现热加载_第3张图片webpack入门实例步骤+使用webpack-dev-server实现热加载_第4张图片

你可能感兴趣的:(webpack)