webpack web-dev-server 熱加載

摘要

坑位:css

  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.html

詳細可見:https://webpack.github.io/docs/hot-module-replacement-with-webpack.htmlwebpack

配置

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"
相關文章
相關標籤/搜索