webpack web-dev-server 热加载

摘要

坑位:

  1. 千万不要webpack.config.js 加了HotModuleReplacementPlugin , web-dev-server 也加hot:true 配置, 会出现莫名的错误, 我这里出现的是 xx.ts -> index.js -> 0 is not accept 的错误

This adds the HotModuleReplacementPlugin. Make sure to use either the --hot flag, or the HotModuleReplacementPlugin in your webpack.config.js, but never both at the same time as in that case, the HMR plugin will actually be added twice, breaking the setup.

详细可见:https://webpack.github.io/docs/hot-module-replacement-with-webpack.html

配置

run.js 文件

var webpack = require("webpack");
// 可换成express 等其他server
var webpackDevServer = require("webpack-dev-server");
var config = require("./webpack.config.js");
var compiler = webpack(config);
var server = new webpackDevServer(compiler, {
    publicPath: config.output.publicPath   // 关键部位!
});
server.listen(3000);

webpack.config.js

const path = require('path'); // 导入路径包
const webpack = require('webpack');

module.exports = {
  context: __dirname,
  devtool: '#inline-source-map',
  entry: [
    "./index.js",
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/dev-server'
  ], // 入口文件
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: "bundle.js",
    publicPath: "http://localhost:3000/build/"   // 关键部位!
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"]
  },
  module: {
    loaders: [
      {test: /.css$/, loader: "style!css"},
      {test: /.scss$/, loader: "style!css!sass"},
      {test: /.ts?$/, loader: "ts-loader" },
    ]
  },
  plugins: [
    new webpack.DefinePlugin({ "global.GENTLY": false }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin()   // 这个插件可以看一些莫名其妙的错误,
  ]
};

package.json

    "webpack": "^3.3.0",
    "webpack-dev-middleware": "^1.11.0",
    "webpack-dev-server": "^2.5.1"
原文地址:https://www.cnblogs.com/huxiaoyun90/p/7217908.html