4

我是 Node JS 的新手。我正在使用 webpack-hot-middleware 创建一个带有热重载的后端 API 服务器。我尝试使用 webpack-dev-middleware 将服务器脚本(index.js)加载到内存并执行该 javascrip t 文件。

这是我的代码:链接

我发现我的代码可以成功地进行热重载,但是我无法加载服务器脚本(index.js)并启动我的 API 服务器。由于某些原因,我想使用 webpack-dev-middleware 而不是 webpack 开发服务器。

这是我的文件结构:

├── package.json.
├── build
|   ├── devserver.js
|   └── webpack.devserver.config.js
├── server
|   └── index.js (code of the API server)
└── dist

我找到了大量关于如何在呈现 HTML 的前端或后端服务器上执行此操作的教程,但我需要启动我的 index.js。

所以,我的问题是如何加载从 webpack-dev-middleware 生成的 js 文件并启动该 js 文件。

以下是我尝试的:

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack.devserver.config');
var StreamCache = require('stream-cache');
var fs = require('fs');

const compiler = webpack(webpackConfig);

const app = express();

const hotMiddleware = webpackHotMiddleware(compiler);
const middleware = webpackMiddleware(compiler, {
    publicPath: "",
    contentBase: 'server',
    stats: {
        colors: true,
        hash: false,
        timings: true,
        chunks: false,
        chunkModules: false,
        modules: false
    }
});
app.use(middleware);
app.use(hotMiddleware);

middleware.waitUntilValid(() => {
    //Then, what should I do??????
  console.log(middleware.fileSystem.readFileSync(path.join(__dirname,               '../dist/backend.js')));
})

在 webpack.devserver.config.js 中:

var fs = require('fs');
var path = require('path');
var webpack = require('webpack');

var nodeModules = {};
fs.readdirSync('node_modules')
    .filter(function (x) {
        return ['.bin'].indexOf(x) === -1;
    })
    .forEach(function (mod) {
        nodeModules[mod] = 'commonjs ' + mod;
    });

module.exports = {
    devtool: 'eval-source-map',
    entry: [
        'webpack/hot/signal.js',
        './server/index.js'
    ],
    target: 'node',
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: 'backend.js',
        publicPath: ''
    },
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.DefinePlugin({

        })
    ],
    recordsPath: path.resolve(__dirname, '../dist/a.json'),
    resolveLoader: {
        moduleExtensions: ['-loader']
    },
    externals: nodeModules,
    watch: true,
    module: {
        rules: [{
                test: /\.js$/,
                loader: 'babel-loader'
            },
            {
                test: /\.es6$/,
                loaders: ['babel-loader']
            },
            {
                test: /\.json?$/,
                loader: 'json'
            }
        ]
    }
};

结果:在 index.js 上更改某些内容后,代码似乎已成功重新加载,但是当我访问 /api/hi API 时看不到更改。

webpack building...
webpack built 4f5191c370239429fae8 in 378ms
Version: webpack 3.10.0
Time: 378ms
     Asset   Size  Chunks             Chunk Names
backend.js  47 kB       0  [emitted]  main
webpack: Compiled successfully.
webpack: Compiling...
webpack building...
webpack built 59489ea86a2ccf081fa6 in 30ms
Version: webpack 3.10.0
Time: 30ms
                           Asset      Size  Chunks             Chunk Names
                      backend.js   47.1 kB       0  [emitted]  main
0.4f5191c370239429fae8.hot-update.js   1.84 kB       0  [emitted]  main
4f5191c370239429fae8.hot-update.json  43 bytes          [emitted]
webpack: Compiled successfully.
4

0 回答 0