webpack自動刷新

webpack.config.jsjavascript

var path = require('path');

module.exports = {
  entry: {
    index:'./js/components/index'
  },
  externals: [{
    'react-dom':'ReactDOM',
    'react':'React'
  }],
  output: {
    path:path.resolve(__dirname,'js/components'),
    filename: 'bundle.js'
  },
  module: {
    loaders:[
    {
      test: /\.js[x]?$/,
      include: path.resolve(__dirname, 'js/components'),
      loader: 'babel',
      query: {
        presets: ['es2015','react']
      }
    },
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
    alias:[
    {'react-dom':'./libs/react-dom.js','react':'./libs/react.js'}
    ]
  }
};

1.htmlhtml

<!DOCTYPE html>
<html>
...
<body>
    <script type="text/javascript" src='/libs/react.js'></script>
    <script type="text/javascript" src='/libs/react-dom.js'></script>
    <script type="text/javascript" src='/js/components/bundle.js'></script>
</body>
</html>

不修改配置文件(推薦)

Iframe mode

  • 運行webpack-dev-serverjava

  • 瀏覽器打開http://localhost:8080/webpack-dev-server/1.htmlreact

Inline mode

  • 在1.html中添加
    <script src="http://localhost:8080/webpack-dev-server.js"></script>webpack

  • 運行webpack-dev-servergit

  • 瀏覽器打開http://localhost:8080/1.htmlgithub

修改配置文件

webpack.config.jsweb

...
module.exports = {
  entry: ['webpack/hot/dev-server','webpack-dev-server/client?http://localhost:8080','./js/components/index'],
  ...
  plugins: [
  new webpack.HotModuleReplacementPlugin()
  ]
};
  • 運行webpack-dev-server,不用添加官網上說的--inline --hot參數json

  • 瀏覽器打開http://localhost:8080/1.html數組

這種方式的缺點:

  • 會生成多餘的js,json文件,而且只能手動刪除

  • 配置文件中的entry只能爲數組,不能用於多個入口的狀況

...
    entry: {
        a: "./a",
        b: "./b",
        c: ["./c", "./d"]
    },
    output: {
        path: path.join(__dirname, "dist"),
        filename: "[name].entry.js"
    }
    ...

上面全部方式都須要先運行webpack -w監聽文件變化


代碼

參考
官網文檔

相關文章
相關標籤/搜索