Coder Social home page Coder Social logo

koa-webpack-middleware's Introduction

koa-webpack-middleware

npm version Circle CI js-standard-style

webpack-dev-middleware for koa2 with HMR(hot module replacement) supports.

Install

$ npm i koa-webpack-middleware -D

Depends

This middleware designd for koa2 ecosystem, make sure installed the right version:

npm i koa@next -S

Usage

See example/ for an example of usage.

import webpack from 'webpack'
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware'
import devConfig from './webpack.config.dev'
const compile = webpack(devConfig)
app.use(devMiddleware(compile, {
    // display no info to console (only warnings and errors)
    noInfo: false,

    // display nothing to the console
    quiet: false,

    // switch into lazy mode
    // that means no watching, but recompilation on every request
    lazy: true,

    // watch options (only lazy: false)
    watchOptions: {
        aggregateTimeout: 300,
        poll: true
    },

    // public path to bind the middleware to
    // use the same as in webpack
    publicPath: "/assets/",

    // custom headers
    headers: { "X-Custom-Header": "yes" },

    // options for formating the statistics
    stats: {
        colors: true
    }
}))
app.use(hotMiddleware(compile, {
  // log: console.log,
  // path: '/__webpack_hmr',
  // heartbeat: 10 * 1000
}))

HMR configure

  1. webpack plugins configure

    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]
  2. webpack entry configure

    $ npm i eventsource-polyfill -D
    entry: {
      'index': [
        // For old browsers
        'eventsource-polyfill',
        'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
        'index.js']
    },
  3. webpack loader configure

    $ npm i babel-preset-es2015 babel-preset-stage-0 -D
    {
      test: /\.js$/,
      loader: 'babel',
      query: {
        'presets': ['es2015', 'stage-0']
        }
      },
      include: './src'
    }

    HMR for react project

    $ npm i babel-preset-react babel-preset-react-hmre -D
    {
      test: /\.jsx?$/,
      loader: 'babel',
      query: {
        'presets': ['es2015', 'stage-0', 'react'],
        'env': {
          'development': {
            'presets': ['react-hmre']
          }
        }
      },
      include: './src'
    }
  4. put the code in your entry file to enable HMR

    React project do not need

    if (module.hot) {
      module.hot.accept()
    }

That's all, you're all set!

koa-webpack-middleware's People

Contributors

clippit avatar g0ne150 avatar gaoqiankun avatar greenkeeper[bot] avatar greenkeeperio-bot avatar leecade avatar neyasov avatar yi-ge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-webpack-middleware's Issues

1.0.4 is broken in NPM registry

Latest v1.0.4 published to NPM is broken and is breaking dependent projects.

The published package is missing the lib/ folder, where the main entry point is declared (lib/index.js).

This is causing failures when importing/requiring the module.

Could you please publish a fixed version?

regeneratorRuntime is not defined

Fixed by adding require('babel-polyfill') to the top of the dev server. Is it possible to add the runtime to the release version so this isn't necessary for people who don't transpile their server code?

Add feature to use fileSystem

I want to use fileSystem like

const htmlBuffer = devMiddleware.fileSystem.readFileSync(`${config.output.path}/index.html`)

for now, I get a error like

TypeError: Cannot read property 'readFileSync' of undefined

I know that devMiddleware from koa-webpack-middleware is a wrapper function of webpack-dev-middleware, has no fileSystem property.

So could you can add this feature ? thanks.

An in-range update of koa is breaking the build 🚨

Version 2.0.1 of koa just got published.

Branch Build failing 🚨
Dependency koa
Current Version 2.0.0
Type peerDependency

This version is covered by your current version range and after updating it in your project the build failed.

As koa is β€œonly” a peerDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Commits

The new version differs by 43 commits (ahead by 43, behind by 1).

  • 6c6aa4d 2.0.1
  • 4e5deae history++
  • 6506108 package: remove publish tag
  • d4b3223 docs++
  • f191c0d package: oops re-add babel-eslint
  • a7c4236 fix: add named arrow function for request and response handlers (#805)
  • cd02834 travis: only test node v7.6.0+
  • 9671add test: remove babel tests as they are no longer needed in node v7.6
  • df7b4ff docs: replace the reference to co
  • 00156df remove unused app.name (#899)
  • 152b6d7 Fix response.status default value documentation (#889)
  • 8435268 Upgrade mocha (#900)
  • d48291f Release 2.0.0-alpha.8
  • 7ae9c3e Fix malformed content-type header causing exception on charset get (#898)
  • 2db3b1b Fix typo for accepts(). (#863)

There are 43 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Middleware for all routes

I configured webpack middleware, when I go to index page / all works fine, otherwise page Not Found, how to make work dev server for all paths ?

server.js

const Koa = require('koa');
const webpack = require('webpack');
const koaWebpack = require('koa-webpack-middleware');
const path = require('path');
const fs = require('fs');

const PORT = 3000;

const app = new Koa();
const config = require('./webpack.config');
const compiler = webpack(config);

app.use(koaWebpack.devMiddleware(compiler, {
  publicPath: config.output.publicPath,
  historyApiFallback: true,
  stats: { colors: true },
}));

app.listen(PORT, function () {
  console.log(`Dev Server port: "${PORT}"`);
});

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  devtool: 'inline-source-map',
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
  module: {
    rules: [
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif|woff|woff2|eot|ttf|otf)$/,
        use: [
          'file-loader',
          {
            loader: 'url-loader',
            options: { limit: 40000 },
          },
          'image-webpack-loader',
        ],
      },
    ],
  },
};

Crash when loading page before bundle ready

The browser gets a Not Found response, the server crashes with

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:504:11)
    at ServerResponse.setHeader (_http_outgoing.js:511:3)
    at Object.set (./node_modules/koa/lib/response.js:440:16)
    at Object.proto.(anonymous function) [as set] (./node_modules/delegates/index.js:40:31)
    at Object.setHeader (./node_modules/koa-webpack-middleware/lib/devMiddleware.js:29:23)
    at Object.handleRangeHeaders (./node_modules/webpack-dev-middleware/lib/Shared.js:61:8)
    at processRequest (./node_modules/webpack-dev-middleware/middleware.js:63:21)
    at continueBecauseBundleAvailable (./node_modules/webpack-dev-middleware/lib/Shared.js:122:6)
    at Array.forEach (native)
    at ./node_modules/webpack-dev-middleware/lib/Shared.js:121:9
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickDomainCallback (internal/process/next_tick.js:198:9)

Even though webpack says webpack: wait until bundle finished: /

I've included the middleware as follows:

app.use(devMiddleware(webpack([config]), {
    watchOptions: {
        aggregateTimeout: 300,
        poll: true
    },
    historyApiFallback: true
}));

I'm using

koa-webpack-middleware@^1.0.5:
  version "1.0.5"

serverSideRender option is not supported

if set serverSideRender to true then will be crash here

`
TypeError: Cannot set property "webpackStats" of undefined

at D:\e\goswami-site\node_modules\webpack-dev-middleware\middleware.js:196:29  
at continueBecauseBundleAvailable (D:\e\goswami-site\node_modules\webpack-dev-middleware\middleware.js:94:5)  
at Array.forEach (native)  
at D:\e\goswami-site\node_modules\webpack-dev-middleware\middleware.js:93:8  
at _combinedTickCallback (internal/process/next_tick.js:67:7)  
at process._tickCallback (internal/process/next_tick.js:98:9)  

`

How to run middleware with other routes

So I tried to convert this app to Koa2. I ran into a couple of issues.

My setup was basically 3 middleware - dev, hot and my catch all route to send the isomorphic code.

The issues I experienced was that I would either get 404 or it would dump my final html to the desktop instead of displaying it. I ended up having to modify this middleware to only accept routes that match the path (just like they have in the express module).

Unfortunately I then ran into another issue of headers being sent - I tracked it down to the script tags in my catch all route html code that call the webpack bundle.

I eventually gave up and am using the webpack dev server CLI but I would love to see a working example of what I am talking about. I could not find any examples in the wild of a single hmr/isomorphic server - everyone seems to do two servers.

ReferenceError: regeneratorRuntime is not defined

Getting:

/[..]/node_modules/koa-webpack-middleware/lib/devMiddleware.js:18
    var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(ctx, next) {
                                 ^

ReferenceError: regeneratorRuntime is not defined
    at /[..]/node_modules/koa-webpack-middleware/lib/devMiddleware.js:18:34
    at Object.exports.default [as devMiddleware] (/[..]/node_modules/koa-webpack-middleware/lib/devMiddleware.js:44:4)
    at Object.<anonymous> (/[..]/server/app.js:20:28)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:425:7)

"koa-webpack-middleware": "^1.0.3",

Using require as babel is not set up (yet) on the backend. Would that cause the issue?

const webpackMiddleware = require('koa-webpack-middleware');
app = app
    .use(webpackMiddleware.devMiddleware(cfg, options))
    .use(webpackMiddleware.hotMiddleware(cfg));

Combine Setup for Efficiency

I'd like to request refactoring to combine all of the setup between dev-middleware and hot-middleware. I've never seen an example where they aren't app.use'd in succession, and given that their options are distinct this should be a trivial refactor:

import packWare from 'koa-webpack-middleware';

app.use(packWare({
  dev: // dev options,
  hot: // hot options,
  compiler: // optional webpack instance,
  config: // optional webpack config. should look for webpack.config.js in root by default
]);

webpack can be imported via a peerDependency entry for the webpack module in package.json, or provided as part of the config of the middleware. This negates the need to set that portion up manually for each use of koa-webpack-middleware.

If you're open to this change, I'll put together a pull request. I'd also be happy to provide an example for Vue.js.

Missing Examples

Looks like someone forgot to put examples in the examples directories.

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.