Giter Site home page Giter Site logo

webpack-dev-middleware's Issues

How to handle changes in backend files (eg. a route file in Express)?

Hello, I'm getting started with Express + Webpack but I'm having a hard to time figuring out what is the best setup to use.

At the moment I am using Weback to bundle all the "frontend" files (i.e. used by the client/browser), so if I change something regarding the client, webpack-dev-middleware works perfectly and it updates the bundle in memory in a fraction of a second.
But if something is changed eg. in a route file, nothing changes and I have to restart the server to see the updates, this implies that webpack-dev-middleware has to create the bundle from scratch and it takes (at the moment) ~6secs. During development, waiting for such time for every changes I make is a bit annoying.

Is there a smarter way of working with this setup? Hope someone can share his experience.
Thanks!

Access memoryfs files

Hi, so I know that this middleware automatically handles the serving of all assets from memory. However, is there a way to let express use this memoryFs for other middleware as well? So that I can, for example, use res.render('myfile.ext') where myfile.ext is also in the webpack-dev memoryFs?

'alias' default lookup directories

Hey @sokra

I'm trying to replace net with net-chromeify

I've put net-chromeify in ./web_modules/ and this works fine on the command-line: webpack src/ComponentLoader.js temp.js --alias net=net-chromeify

I'm trying to do the same thing with webpack-dev-middleware. My config in main.js is this:

app.use(require('webpack-dev-middleware')(__dirname, "./src/ComponentLoader", {
  webpack: {
    watch: true,
    debug: true,
    publicPrefix: "http://localhost:3000/scripts/",
    output: "bundle.js",
    libary: "ComponentLoader",
    alias: {net: "net-chromeify"} //I've also tried moving it outside the webpack hash
  }
})); 

but it can't seem to find net-chromeify. The error suggests that it's looking for net and not net-chromeify:

ERROR: Cannot find module 'net'
Error: Module "net" not found in context "/Users/rainerdreyer/Workspace/PipeDream/components"
Error: /Users/rainerdreyer/Workspace/PipeDream/node_modules/webpack-dev-middleware/node_modules/webpack/buildin/net is not a directory
@ /Users/rainerdreyer/Workspace/PipeDream/components/ServerEndpoint.js (line 2, column 8)

net is not a directory...

Why is it looking for net and not net-chromeify?

Thanks! :)

Giving access to files outside of contentBase:...

after a great start:
yo react-webpack
yo react-webpack:component foo
grunt serve...

How do I allow access to the node_modules or bower_components directory in the index.html file?

My current solution was to use a grunt task to copy the files from the ./node_modules/... directory to the src/styles/vendor/... directory.
...
copy: {
dev: {
files: [
{
src: [__dirname + '/node_modules/bootstrap/dist/css/bootstrap.min.css' ],
dest: '<%= pkg.src %>/styles/vendor/bootstrap.min.css'
}
]
},
...

For development purposes I would rather have something like:

...index.html
<link href="/node_modules/bootstrap/dist/css/bootstrap.min.css" media="all" rel="stylesheet" />

`lazy: true` won't ever trigger rebuild without undocumented option "filename" set.

I have it narrowed down to line 135 of middleware.js:

if(options.lazy && filename === pathJoin(compiler.outputPath, options.filename))

When the undocumented option filename isn't set, it will attempt to match /Users/tom/Documents/somewebsite/dist/undefined, fail, and the request will fall through to the next handler, regardless of the file.

Setting { lazy: true, filename: "client.js" } in the dev-middleware config allows it to handle the request, but this won't work for webpack configurations with multiple entry points.

'indexOf' of undefined on url.indexOf(localPrefix)

Hi,

I just update to v1.6.0 and a error occurred

TypeError: Cannot read property 'indexOf' of undefined
   at getFilenameFromUrl (/home/zckrs/project/node_modules/webpack-dev-middleware/middleware.js:129:9)
   at webpackDevMiddleware (/home/zckrs/project/node_modules/webpack-dev-middleware/middleware.js:174:18)
   at call (/home/zckrs/project/node_modules/connect/index.js:239:7)
   at next (/home/zckrs/project/node_modules/connect/index.js:183:5)
...
...

Hot module replacement support?

I'm trying to enable hot module replacement support, but webpack-dev-middleware doen't seem to be capturing requests for /socket.io/1/?t=1423..., which end up falling through to regular page routing.

In my Gruntfile.js (it's the very first middleware):

middlewares.unshift(webpackMiddleware(
  webpack(webpackConfig(['client', 'dev'])), {
    hot: true,
    noInfo: true,
    stats: { color: true }
  }));

Relevant parts of webpack.config.js:

    entry: {
      client: [
        'webpack-dev-server/client?http://localhost:9001',
        'webpack/hot/only-dev-server',
        'client.jsx'
      ]
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('development')
        }
      }),
      new webpack.HotModuleReplacementPlugin()
    ]

Is this possible to do within the middleware only?

FOUC when using HMR with CSS source-map.

When I use hot-module-reloading with sourcemaps I see what used to be inline style tags in the head turn into link tags with blob: hrefs. For some reason this change is causing a flash of unstyled content before the link tags are injected into the head.

Are there any workarounds for this?

Conflict with html-webpack-plugin on catch all route

I have a single page app and I am using the middleware during dev. I want to route all requests in express to the index.html file so that my spa router takes over. There seems to be a problem with webpack-dev-middleware trying to detect the file or path, which prevents me from rendering the index.html file with the html-webpack-plugin.

Here is essentially what I have:

// webpack.config
    new HtmlWebpackPlugin({
      template : paths.src('index.html'),
      hash     : true,
      filename : 'index.html',
      inject   : 'body'
    })

// server.js
const devMiddleware = WebpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath,
  contentBase: paths.project(config.get('dir_src')),
  hot: true,
  quiet: true,
  noInfo: false,
  lazy: false,
  stats: {
    colors: true
  },
  historyApiFallback: true
});
app.use(devMiddleware);

app.use((req, res, next) => {
  console.log('Final Request', req.url, req.method, req.accepts('html'));
  if (req.method === 'GET' && req.accepts('html')) {
    //res.sendFile(paths.src('index.html'), err => err && next());
    res.write(devMiddleware.fileSystem.readFileSync(paths.src('index.html')));
    res.send();
    next();
  } else next();
});

This results in the following error:

Error: no such file or directory
   at MemoryFileSystem.readFileSync (node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:107:10)
   at build/webpack-dev-server.js:74:40
   at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (node_modules/express/lib/router/index.js:312:13)
   at node_modules/express/lib/router/index.js:280:7
   at Function.process_params (node_modules/express/lib/router/index.js:330:12)
   at next (node_modules/express/lib/router/index.js:271:10)
   at middleware (node_modules/webpack-hot-middleware/middleware.js:32:48)
   at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (node_modules/express/lib/router/index.js:312:13)
   at node_modules/express/lib/router/index.js:280:7
   at Function.process_params (node_modules/express/lib/router/index.js:330:12)
   at next (node_modules/express/lib/router/index.js:271:10)
   at node_modules/webpack-dev-middleware/middleware.js:166:12
   at continueBecauseBundleAvailible (node_modules/webpack-dev-middleware/middleware.js:58:5)
   at Array.forEach (native)

I confirmed the path is correct and could be read with: fs.readFileSync(paths.src('index.html')). However it appears the upstream library may have an issue.

Spinning within docker?

Hi, I was just wondering if I could get some insight into this module. I'm using this in a project running a Node server, but have been porting to use Docker. In Docker, I start bash and start running the Node server as I typically do, but the Webpack watcher perpetually spins. It creates itself and then automatically invalidates itself and rebuilds.

Could you offer any insight into what would cause the middleware to spin?

req.path is sometimes not defined

As of #78, I am noticing that req.path is not always defined. I am using Express 4 here and have found a little information, but it doesn't explain the why. The OP mentions "positioning of middleware", but I am unsure how that might trigger this bug. Overall, I'm wondering what the advantage is of using req.path vs req.url. Here's the stack trace:

TypeError: Cannot read property 'indexOf' of undefined
    at getFilenameFromUrl (/Users/stephenmarshall/code/singular-web-server/node_modules/webpack-dev-middleware/middleware.js:129:9)
    at webpackDevMiddleware (/Users/stephenmarshall/code/singular-web-server/node_modules/webpack-dev-middleware/middleware.js:175:18)
    at call (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:239:7)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:183:5)
    at handleIe (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/foxy/lib/utils.js:191:5)
    at call (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:239:7)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:183:5)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:161:14)
    at Function.handle (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:186:3)
    at Server.app (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:51:37)
    at Server.<anonymous> (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/socket.io/node_modules/engine.io/lib/server.js:434:22)
    at Server.<anonymous> (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/socket.io/lib/index.js:260:16)
    at emitTwo (events.js:87:13)
    at Server.emit (events.js:172:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)

base64 encoded output???

I am getting base64 encoded code when using 1.5.0/1.5.1 (with webpack 1 and webpack-hot-middleware). Works just fine with 1.2.0 - 1.4.0.
So, basically, in dev mode, when I go to http://localhost:3000/static/app.js I should see something like

/******/ (function(modules) { // webpackBootstrap
/******/    var parentHotUpdateCallback = this["webpackHotUpdate"];
/******/    this["webpackHotUpdate"] = 
....

instead I get

"LyoqKioqKi8gKGZ1bmN0aW9uKG1vZHVs...
...
...qKiovIF0pOw=="

which is the base64 encoding of the app code.
Any idea what's going on?

Doesn't reload the browser after re-compiling

I'm not sure it's a bug but I'm trying to switch from watch-build cycle to using of connect + middleware. The only problem is that after recompiling the bundle browser doesn't reload it. If I do manual refresh I can see an updated bundle. Please advise where I can look for it.

Does this work with hot loading?

I see WebpackDevServer comes with special support for hot loading. Middleware does not seem to include it. Is it possible to use the middleware with hot loading somehow?

Does it support proxy config like webpack-dev-server?

`var express = require('express')
var webpack = require('webpack')

var app = express()
var compiler = webpack(config)

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
proxy: {
'/xxx*': {
target: 'http://1.2.3.4:8080/aaa'
}
},
stats: {
colors: true,
chunks: false
}
}))`

I tried this but it seems not working for proxy

two babel config issue

Hi

I have a server which is using babel-register and .babelrc. It is working fine.
The problem is with this library or webpack library. I am trying to use a different settings for the babel but without any success. WebpackDevMiddleware will always use config from the .babelrc loaded by babel-register. I am not sure maybe it is not possible to set a different babel config with babel-register.

Here is a small example

const differentBabelConfig = {
  // other babel config different form .babelrc
};

const compiler = new webpack({
// ...
{ test: /\.(js|jsx)$/, exclude: /node_modules\/(?!cherry)/, loader: 'babel-loader', query: differentBabelConfig },
// ... 
})

Thank you for any help with it

I get the following issue on "npm start"

/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack-dev-middleware/middleware.js:104
            if(err) throw err;
                    ^
Error: invalid argument
    at pathToArray (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:229:25)
    at Compiler.applyPluginsAsync (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/tapable/lib/Tapable.js:61:69)
    at Compiler.emitAssets (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:226:7)
    at Watching.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:54:18)
    at /home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:403:12
    at Compiler.next (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/tapable/lib/Tapable.js:68:11)
    at Compiler.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/CachePlugin.js:40:4)

This is my configuration file

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfigBuilder from '../webpack.config';

const webpackConfig = webpackConfigBuilder('development');
const config = webpack(webpackConfig);

let app = express();

const compiler = webpack(config);
const middleware = webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  contentBase: 'src',
  stats: {
    colors: true,
    hash: false,
    timings: true,
    chunks: false,
    chunkModules: false,
    modules: false
  }
});

app.use(middleware);
app.use(webpackHotMiddleware(compiler));
app.get('/test', function response(req, res) {
  res.write(middleware.fileSystem.readFileSync(__dirname+"/../dist/index.html"));
  res.end();
});

app.listen(8089, function onStart(err) {
  if(err) {
    console.log(err);
  }
  console.info("Listening on 8089, open in browser");
});

Where am I going wrong?

Higher CPU load than webpack-dev-server?

I was playing around with making my own asset server (to replace webpack-dev-server) and noticed that it causes a huge spike in CPU load (~100% with fans spinning) compared to the dev server (~3%) when both are just idling.

These are just measured using Activity Monitor on a 10.9.5 Macbook Pro (quad core i7, 16GB RAM). Don't think the specs of the machine are super relevant, but there's definitely a noticeable difference when switching between the two and wanted to see if anyone had input.

Warnings and Errors only

How can I use this middleware and only get logging information about errors and warnings only, not full stats?

Hot reload fails to download patch when public path is specified

Trying to proxy server and mount js file in expected dev build location in webpack-dev-server grunt config to intercept requests for http://localhost:6001/slm/js/alm/builds/components/alm-components.js
...
publicPath: '/slm/js/alm/builds/components'

This works now but hot reloading is no longer able to find the update chunks at /af64be6a5c4098fd56ce.hot-update.json

but works if public path is specified:
curl http://localhost:6001/slm/js/alm/builds/components/af64be6a5c4098fd56ce.hot-update.json
{"h":"1da04cff58307a4c0143","c":[0]}

It seems that it still needs to expect update chunks to be at root or hot reload module needs to know the public path.

webpack 2, ids collision

have many entry points.

        "vendor": ["lodash", "backbone", .... ],
        "common": ["common/module1", "common/module2"..." ],
        "page1": "page1",
        "page2": "page2",

...
     new CommonsChunkPlugin({
            // The order of this array matters
            names: [ "rest", "common", "vendor" ],
            minChunks: 3
        }),

Same Id assigned to modules in different chunks.
Have not good and small reproduce( our project have >1000 modules )
Probably its because each chunk loaded independently and at same time?

Production bundles via "webpack" generated fine.

devMiddleware.fileSystem.readFileSync not work with gulp

Hi, @sokra , I'm getting started with webpack-dev-middleware and Gulp, but I have trouble with webpack-dev-middleware. In development mode, when I start the server by npm start, it's normal. However, I use Gulp task to start the server, an error happened:

Error: no such file or directory
   at MemoryFileSystem.readFileSync (d:\sources\modern-java-web-scaffold\frontend\node_modules\memory-fs\lib\MemoryFileSystem.js:114:10)
   at d:\sources\modern-java-web-scaffold\frontend\gulpfile.js:80:44
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at next (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:277:22
   at param (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:349:14)
   at param (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:365:14)
   at Function.process_params (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:410:3)
   at next (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:271:10)
   at favicon (d:\sources\modern-java-web-scaffold\frontend\node_modules\serve-favicon\index.js:72:7)
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at trim_prefix (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:312:13)
   at d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:280:7
   at Function.process_params (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:330:12)

The main code in gulpfile.js as following:

gulp.task('dev-server', ['build-dev'], () => {
    const compiler = webpack(devConfig);
    const devMiddleware = webpackDevMiddleware(compiler, {
        publicPath: devConfig.output.publicPath,
        contentBase: 'src',
        stats: {
            colors: true,
            hash: false,
            timings: true,
            chunks: false,
            chunkModules: false,
            modules: false
        }
    });

    app.use(devMiddleware);
    app.use(webpackHotMiddleware(compiler));
    configFavicon(app);
    app.get('*', (req, res) => {
        res.write(devMiddleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html')));
        res.end();
    });

    app.listen(port, '0.0.0.0', err => {
            if (err) throw new gutil.PluginError('dev-server', err);
            gutil.log('[dev-server]', '==> Listening on port ' + port + '. Open up http://0.0.0.0:' + port + '/ in your browser.');
    });
});

And this is my project's address: modern-java-web-scaffold. Is there something wrong with me? Could you give me some advice or solutions.
Thanks in advance.

Invalid argument

I am getting the following error trying to build my bundle. Can anyone help?

Error: invalid argument
    at pathToArray (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:229:25)
    at Compiler.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Compiler.emitAssets (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:226:7)
    at Watching.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:54:18)
    at /Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:403:12
    at Compiler.next (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:67:11)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/CachePlugin.js:40:4)
    at Compiler.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:400:9)
    at Compilation.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compilation.js:577:13)
    at Compilation.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Compilation.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compilation.js:572:10)
    at Compilation.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)

How to build files for production?

Hi,

I'm using the middleware and it works really smooth for development. As far as I understood, the middleware serves the files from the memory. But how do I build the files for development? How can I put them on disk? I could not figure it out.

Thanks for your help!
Jan

Quiet and noInfo options not suppressing logs in browser

Hi,

I'm using the API and setting quiet and noInfo to true as follows:

  new WebpackDevServer(webpack(webpackConfig.client), {
    publicPath: webpackConfig.client.output.publicPath,
    hot: true,
    quiet: true,
    noInfo: true
  }).listen(4000, 'localhost', function (err, result) {
    if(err) {
      console.log('error', err);
    }
    else {
      console.log('info', "dev server listening on 4000");
    }
  });

When I run the server node devServer.js I simply get the dev server listening on 4000 message and no other output which is what I want.

When I visit my app in the browser though, which includes the following:

<script src="http://localhost:4000/bundle/client.js"></script>

My browser's console is spammed with socket logs. Is this expected? Shouldn't the quiet option prevent this?

what is the endpoint?

assuming a configuration like this:

var express = require('express');
var webpack = require('webpack');
var webpackMiddleware = require('webpack-dev-middleware');

var app = express();

app.use(webpackMiddleware(webpack({
  entry: "mocha!./test/all.js",
  output: {
    path: "/"
  }
})));

app.listen(8000);

Where all.js contains some mocha tests... what is the resulting endpoint to view them? http://localhost:8000/bundle.js shows me the bundle, but I don't know how to get to the test suite runner html?

Auto-reloading files on Windows not working without webpack-hot-middleware

Hi, it seems that the auto-reload (not hot module replacement, just the refreshing of files over websockets) feature of webpack-dev-middleware does not appear to be working on Windows at the moment.

I think it may be a similar issue to what was previously reported with webpack-dev-server: webpack/webpack-dev-server#155

I set the middleware to log out to the console, and I can see that it's getting rebuilt every time on file saves, but it just doesn't communicate back to the browser without a manual page refresh.

What's strange is everything appears to work as it should when including webpack-hot-middleware along with it. However, a lot of people are starting to remove webpack-hot-middleware from their projects for a few different reasons:

  1. The future of how hot reloading will be accomplished (at least in React) seems to still be up in the air... Some are wanting to back out of it for now until new methods are established,
  2. Hot reloading does not currently work with purely functional React components, and many are choosing to go this route now with libraries like recompose out there to help make it more easily achievable.

Ideally, we should be able to at least take advantage of the auto-reload feature without the use of webpack-hot-middleware, but I can't pinpoint what's causing it to break at the moment. Anyone have any ideas?

hot reload fails when using Webstorm 2016.1

I found that hot reload stopped working when I upgraded Webstorm as below, so copying in here from https://youtrack.jetbrains.com/issue/WEB-21174 in case it helps anyone:

I have this issue as well, I updated from 11.0.3 to 2016.1 and hot reload is broken. Unselecting the "safe write" option resolves the issue. (Appearance and behaviour > System Settings > Synchronization) Hot reload was working fine in 11.0.3 without changing this option, so I think this is something for you to address.

compiler.plugin is not a function

I'm following the Browsersync - Webpack + React Hot Loader / React Transform HMR recipes trying to add hot-loader into my Gulp build system, but, I'm seeing the following error and I'm not sure to understand how this works in order to determine if this is an issue.

[19:41:07] TypeError: compiler.plugin is not a function
    at module.exports (Z:\development\reactjs\node_modules\webpack-dev-middleware\middleware.js:35:11)
    at Gulp.<anonymous> (Z:\development\reactjs\gulpfile.js:271:17)
    at module.exports (Z:\development\reactjs\node_modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (Z:\development\reactjs\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (Z:\development\reactjs\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (Z:\development\reactjs\node_modules\orchestrator\index.js:134:8)
    at C:\Users\geedmo\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
    at doNTCallback0 (node.js:419:9)
    at process._tickCallback (node.js:348:13)
    at Function.Module.runMain (module.js:469:11)

Any thoughts?

Emitting event to window

Hey, I'm wondering if we can see when there is a module update from within the app. This would allow us to 'refresh' the page within a SPA to get the latest changes. I'm imagining some event that we can watch from the window object.

Options to exclude files

Hey @sokra!

I just had some troubles on osx and the max. file watcher limit.
Is it possible to exclude certain folders via options?

Excluding node_modules would probably solve my problems.

Invalid argument in watchOptions

I'm getting this error

D:\my-path\node_modules\webpack-dev-middleware\middleware.js:107
                        if(err) throw err;
                                ^
 Error: invalid argument
    at pathToArray (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (D:\my-path\node_modules\webpack\lib\Compiler.js:229:25)
    at Compiler.applyPluginsAsync (D:\my-path\node_modules\tapable\lib\Tapable.js:60:69)
    at Compiler.emitAssets (D:\my-path\node_modules\webpack\lib\Compiler.js:226:7)
    at Watching.<anonymous> (D:\my-path\node_modules\webpack\lib\Compiler.js:54:18)
    at D:\my-path\node_modules\webpack\lib\Compiler.js:403:12
    at Compiler.next (D:\my-path\node_modules\tapable\lib\Tapable.js:67:11)
    at Compiler.<anonymous> (D:\my-path\node_modules\webpack\lib\CachePlugin.js:40:4)

This is the code that throws an error:

    if(!options.lazy) {
        var watching = compiler.watch(options.watchOptions, function(err) {
            if(err) throw err;
        });
    } else {
        state = true;
    }

Error object:

{ [Error: invalid argument]
  code: 'EINVAL',
  errno: 18,
  message: 'invalid argument',
  path: 'build\\js' }

Watch options I'm passing:

watchOptions: {
        aggregateTimeout: 100
    }

if there is lazy : true option - everything works fine

[HMR] Update check failed: SyntaxError: Unexpected token <

I'm having an issue with hot module reloading on this repo.

I receive the following error:

[HMR] Update check failed: SyntaxError: Unexpected token <
  at Object.parse (native)
  at XMLHttpRequest.request.onreadystatechange (http://localhost:3000/js/client.js:44:33)

The error comes from within hotDownloadManifest. The request.responseText is HTML, rather than the usual json. This gets passed into JSON.parse which throws. I cannot work out why responseText is HTML.

This repo has a fair amount of CSS split into different files. If I remove a few on the CSS imports it works (most of the time), so my best guess is that it's something to do with a file limit. Could this be the case?

Outdated version on NPM ?

Hi,

it looks like the version installed via NPM is not the same as the one visible here in the repo.
Especially, the waitUntilValid function is not referenced anywhere.

Any clue about that ?
Thank you.

How to use this module with HapiJS ecosystem?

Can you provide an example of how to use this plugin with HapiJS ecosystem?

Below is the configuration i used with Hapi. Thats all i have configured. When i open my server @ localhost:3000 i got an error as below screen shot

webpack-dev-middleware

'use strict';

/* global __dirname */

const Webpack = require('webpack');
const Path = require('path');

module.exports = {
  'devtool': 'eval',
  'entry': [
    'webpack-hot-middleware/client?path=/__webpack_hmr&reload=true',
    './app/main.js'
  ],
  'output':{
    'path': __dirname + '/public/',
    'filename' : 'bundle.js',
    'publicPath' : '/'
  },
  'plugins':[
    new Webpack.optimize.OccurenceOrderPlugin(),
    new Webpack.HotModuleReplacementPlugin(),
    new Webpack.NoErrorsPlugin()
  ],
  'module': {
    'loaders':[
      {
        'test': /\.js$/,
        'include': Path.join(__dirname, 'app'),
        'loader': 'babel-loader'
      }
    ]
  }
};

Option for compact console info

Hello!
It would be greate, if was an option for compact info in console instead of full list of all depeneds in bundle.
It needs for knowing when bundle compiled after change without watching full deps list

Node 6 Compile issues

After updating to Node 6 I am now getting the following issues:

(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.

==== JS stack trace =========================================

Security context: 0x641b9ec9fa9 <JS Object>#0#
    1: .node [module.js:568] [pc=0x31a5c5dec944] (this=0x766c05fe979 <an Object with map 0x34b7d5a90559>#1#,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    2: load [module.js:~447] [pc=0x31a5c587cc36] (this=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    3: tryModuleLoad(aka tryModuleLoad) [module.js:415] [pc=0x31a5c543899d] (this=0x641b9e04189 <undefined>,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x
==== C stack trace ===============================

 1: v8::Template::Set(v8::Local<v8::Name>, v8::Local<v8::Data>, v8::PropertyAttribute)
 2: fse::FSEvents::Initialize(v8::Local<v8::Object>)
 3: node::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&)
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&))
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::(anonymous namespace)::BuiltinArguments<(v8::internal::BuiltinExtraArguments)1>)
 6: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*)
 7: 0x31a5c530961b
 8: 0x31a5c5dec944
(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.

==== JS stack trace =========================================

Security context: 0x641b9ec9fa9 <JS Object>#0#
    1: .node [module.js:568] [pc=0x31a5c5dec944] (this=0x766c05fe979 <an Object with map 0x34b7d5a90559>#1#,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    2: load [module.js:~447] [pc=0x31a5c587cc36] (this=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    3: tryModuleLoad(aka tryModuleLoad) [module.js:415] [pc=0x31a5c543899d] (this=0x641b9e04189 <undefined>,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x
==== C stack trace ===============================

 1: v8::Template::Set(v8::Local<v8::Name>, v8::Local<v8::Data>, v8::PropertyAttribute)
 2: fse::FSEvents::Initialize(v8::Local<v8::Object>)
 3: node::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&)
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&))
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::(anonymous namespace)::BuiltinArguments<(v8::internal::BuiltinExtraArguments)1>)
 6: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*)
 7: 0x31a5c530961b
 8: 0x31a5c5dec944

webpack-dev问题

Dev的時候可以跑 api server + webpack-dev-server(hot load)
Production的時候可以跑 api server + webpack build
有什么解决方案?

Issue when making concurrent requests

There seems to be an issue when making multiple concurrent requests to webpack-dev-middleware simultaneously. I am using the following config:

{
        lazy:true, 
        publicPath:'/build/',
        filename: "commons.js",
        noInfo: false
}

I have webpack middleware included as part of my dev server which also includes tinyLr for automatic reloading. I am not using the full webpack dev server because I also have my dev server configured to mock my server-side. This all works fine if I have one browser open, but if I have two browsers open to my site at the same time, the server crashes as soon as both browsers try to reload at once. I get the below error message:

/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71
        plugins[this._currentPluginApply].apply(this, args);
                                          ^
TypeError: Cannot call method 'apply' of undefined
    at Tapable.next (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:37)
    at done (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/async/lib/async.js:135:19)
    at /Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/async/lib/async.js:32:16
    at /Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/lib/CachePlugin.js:33:6
    at Storage.finished (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:38:16)
    at Object.oncomplete (evalmachine.<anonymous>:107:15)

Issue on updating to 1.5.0

Getting an issue from 1.4.1 to 1.5.0 and seems to be from https://github.com/webpack/webpack-dev-middleware/pull/27/files but not sure if it's a package issue or on my side.

TypeError: res.send is not a function
    at processRequest (/app/node_modules/webpack-dev-middleware/middleware.js:189:8)
    at ready (/app/node_modules/webpack-dev-middleware/middleware.js:96:20)
    at webpackDevMiddleware (/app/node_modules/webpack-dev-middleware/middleware.js:162:3)

Not working on mac

I am not sure whether the problem is caused from webpack-dev-middleware

here are the broken codes:

let compiler = webpack(config);
_rootExpressApp.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
}));
_rootExpressApp.use(webpackHotMiddleware(compiler));

the codes are modified from react-transform-boilerplate

my project worked properly on windows but got 404 error when I request the bundle.js on mac

why the middleware was just passed through and didn't send back any scripts on mac?

Not recompiling after file changes

I'm using webpack-dev-middleware on my express app. Everything looks as expected when I start my app. When I'm making changes as its running, I'm not seeing assets recompile. The documentation gives the impression that it's in watch mode by default and "the compiler recompiles on file changes". Is there something obvious I'm missing? Are there other examples that use webpack-dev-middleware? (other than webpack-dev-server).

Any help is appreciated.

Setup

var webpack = require("webpack");
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackConfig = require('../webpack.config');
var compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler));

Config (Note: publicPath is temporarily set to the dev publicPath).

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

    entry: {
        lib: ['react', 'react-router'],
        main: './app/client.js'
    },

    output: {
        path: __dirname + '/public',
        filename: '/bundle.js',
        publicPath: 'http://localhost:3000'
    },

    resolve: {
        extensions: ['', '.js', '.jsx', '.scss'],
        moduleDirectories: ['node_modules', 'bower_components']
    },

    module: {
        loaders: [
            { test: /\.(js|jsx)$/, loader: 'jsx-loader' },
            { test: /\.scss$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader') },
            { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
            { test: /\.(png|jpg)$/, loader: 'file-loader' }
        ]
    },

    plugins: [
        new ExtractTextPlugin('global.css')
    ]
};

Support History API urls

Hey there,

I am using webpack-dev-middleware to develop a SPA, with an index.html which is programatically generated by webpack. With this plugin, if I navigate to anything other than / or /index.html, the middleware does not pick up the request, and the request fails.

For most people, something like this solves the problem:

app.get('*', function (req, res) {
  res.send(path.join(__dirname, 'index.html'))
}

but for previously mentioned reasons, this doesn't work. I have written this handler to catch urls missed by webpack-dev-middleware, but would look at adding this into the core.

app.use(function (req, res, next) {
  if (req.url.match(/^(\/[a-zA-Z-]+)+(.html)?(\?.+)?$/)) { // Just a regex I spun up to sort my use case
    devMiddleware(
      {
        url: '/index.html'
      },
      res,
      next
    )
  } else {
    next()
  }
})

Forgive me if I've completely missed a config flag or something - I have looked at the source and couldn't find anything.

I am happy to help write a PR to support this, especially since this will become more popular with react-transform becoming more popular.

Thanks for your help in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.