Webpack-Dev-Server与Gulp代码更改后不重新加载

时间:2016-08-16 19:31:14

标签: javascript gulp webpack webpack-dev-server

我是webpack的新手,我试图让它与gulp一起工作。我正在使用以下链接中找到的指南,但它似乎无法正常工作:

https://webpack.github.io/docs/usage-with-gulp.html

谁能告诉我哪部分配置错了?

gulpfile.js

import gulp from 'gulp';
import webpack from 'webpack';
import gutil from "gulp-util";
import WebpackDevServer from "webpack-dev-server";

import webpackConfig from './webpack.config';

gulp.task("dev-server", function(callback) {
    // Start a webpack-dev-server
    var compiler = webpack(webpackConfig);

    new WebpackDevServer(compiler, {

    }).listen(4000, "localhost", function(err) {
        if(err) throw new gutil.PluginError("webpack-dev-server", err);
        // Server listening
        gutil.log("[webpack-dev-server]", "http://localhost:4000/webpack-dev-server/index.html");

        // keep the server alive or continue?
        // callback();
    });
});

webpack.config.js

const path = require("path");

module.exports = {
    watch: true,
    entry: {
        app: __dirname+'/dev/index.js'
    },
    output: {
        path: path.join(__dirname, "dist"),
        filename: '[name].js'
    },
    module: {
        loaders: [
            {test: /\.js$/, loaders: ['babel']},
            {test: /\.scss$/, loaders: ["style", "css", "sass"]}
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

differences between the Node.js API and the CLI for webpack dev server。您正在使用Node.js API,因此应在此处查看:https://webpack.js.org/guides/hot-module-replacement/#via-the-node-js-api

在gulp任务定义函数中尝试以下方法:

// Add entry points for '/webpack-dev-server/client/index.js' necessary for live reloading
WebpackDevServer.addDevServerEntrypoints(webpackConfig, { ... dev-server-options ...});

// Start a webpack-dev-server
var compiler = webpack(webpackConfig);

new WebpackDevServer(compiler, {

}).listen(4000, "localhost", function(err) {
    if(err) throw new gutil.PluginError("webpack-dev-server", err);
    // Server listening
    gutil.log("[webpack-dev-server]", "http://localhost:4000/webpack-dev-server/index.html");

    // keep the server alive or continue?
    // callback();
});

基本上将一行WebpackDevServer.addDevServerEntrypoints(webpackConfig, { ... dev-server-options ...});添加到任务功能的开头。这会将“ /webpack-dev-server/client/index.js”添加为您的webpack配置的条目,并且是实时重新加载所必需的。