1. 程式人生 > >node+webpack(二)webpack-dev-server

node+webpack(二)webpack-dev-server

npm i webpack-dev-server

1.修改package.json

新增

"dev": "webpack-dev-server --config webpack.config.js"

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server --config webpack.config.js"
  },

 

2.設定環境變數

npm i cross-env          不通平臺執行統一指令碼,設定環境變數

修改package.json中的build和dev

修改為

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
  },

3.修改webpack.config.js

   3.1

新增 target:'web',

module.exports={
    target:'web',
    entry: path.join(__dirname,'src/index.js'),
    。。。。。。。

  3.2

   新增 const isDev=process.env.NODE_DEV === 'development'

  3.3

module.exports  修改為  config

新增  module.exports=config

 3.4 

新增

if(isDev){
 config.devServer = {
   port: 8000,
   host: '0.0.0.0',
   overlay: {
     error:true,
   }
 }
}

4.安裝html-webpack-plugin

   4.1 npm i html-webpack-plugin

   4.2 在webpack.config.js加入

 

const HTMLPlugin = require('html-webpack-plugin')

   4.3 webpack.config.js修改為

plugins:[
        new VueLoaderPlugin(),
        new webpack.DefinePlugin({
          'process.env' : {
            NODE_ENV : isDev ? '"development"' : '"production"'
          }
        }),
        new HTMLPlugin()
    ]

      4.4

const webpack = require('webpack')

5.啟動

npm run dev

訪問 http://localhost:8080/

 


熱載入功能

1.修改webpack.config.js

if(isDev){
  config.devServer = {
    port: 8000,
    host: '0.0.0.0',
    overlay: {
      error:true,
    }
  }
 }

加入 hot:true   及   config.plugins.push

加入config.devtool

修改後

if(isDev){
  config.devtool = '#cheap-module-eval-source-map'
  config.devServer = {
    port: 8000,
    host: '0.0.0.0',
    overlay: {
      error:true,
    },
    // open:true,
    hot:true
  }
    config.plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin()
    )
 }