express + react 項目配置熱替換

介紹
// TODO
主要使用三個庫
webpack-dev-middleware
webpack-hot-middleware
react-hot-loadernode

使用例子:react


在 nodejs 項目的 app.js 裏面配置webpack

// 設置頁面目錄
app.set("views", path.join(__dirname, "public/ejs"));
app.set("view engine", "ejs");

// webpack-dev-middleware
if (process.env.NODE_ENV === "development") {
  const webpack = require("webpack");
  const webpackDevMiddleware = require("webpack-dev-middleware");
  const webpackConfig = require("./webpack/dev");
  const compiler = webpack(webpackConfig);

  app.use(
    webpackDevMiddleware(compiler, {
      publicPath: webpackConfig.output.publicPath,
      noInfo: true
    })
  );
  app.use(require("webpack-hot-middleware")(compiler));
}
// 靜態資源的引用路徑
app.use(express.static(path.join(__dirname, "public")));

在 webpack/dev.js 裏面配置web

module.exports = {
  // 開啓緩存。第一次編譯會比較慢,以後編譯速度很是快
  cache: true,
  // 開啓源碼 map 文件功能
  devtool: "cheap-module-source-map",
  devServer: {
    hot: true,
    inline: true,
    compress: true,
    historyApiFallback: true,
    overlay: true
  },
  entry: {
    index: [ // 能夠根據我的場景自定義
      require.resolve("react-hot-loader/patch"),
      require.resolve("webpack-hot-middleware/client"),
      path.join(__dirname, "../public/src/js/index.js")
    ]
  },
 output: {
    path: path.join(__dirname, "../public/build/"),
    filename: "[name].js",
    chunkFilename: "[id].js",
    publicPath: `http://localhost:${process.env.PORT}/build/` // 這裏的路徑配置很重要,不然頁面會找不到
  },
// TODO 
}

react 項目的入口文件處配置express

import { AppContainer } from "react-hot-loader";

ReactDOM.render(
  <AppContainer>
    <Provider store={store}>
      <RouteIndex />
    </Provider>
  </AppContainer>,
  document.querySelector("#root")
);

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept("./routes", () => {
    const NextRoot = require("./routes").default;
    ReactDOM.render(
      <AppContainer>
        <Provider store={store}>
          <NextRoot key={`root${Math.random()}`} />
        </Provider>
      </AppContainer>,
      document.querySelector("#root")
    );
  });
}
相關文章
相關標籤/搜索