• Stars
    star
    337
  • Rank 124,809 (Top 3 %)
  • Language
    JavaScript
  • License
    Mozilla Public Li...
  • Created about 6 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Development Server in a Webpack Plugin
webpack-plugin-serve

tests cover size libera manifesto

webpack-plugin-serve

A Webpack development server in a plugin.

Be sure to browse our recipes and peruse the FAQ after reading the documentation below.

Please consider donating if you find this project useful.

Requirements

webpack-plugin-serve is an evergreen 🌲 module.

This module requires an Active LTS Node version (v10.0.0+). The client scripts in this module require browsers which support async/await. Users may also choose to compile the client script via an appropriately configured Babel webpack loader for use in older browsers.

Feature Parity

In many ways, webpack-plugin-serve stands out from the alternatives. Feature parity with existing solutions is a high priority. If a feature you've come to expect in an alternative isn't directly available, it's likely easy to implement via middleware. Feel free to open an issue for direction.

For those interested in direct comparisons, please see the Feature Grid for a breakdown of feature comparisons between webpack-plugin-serve and the alternatives.

Install

Using npm:

npm install webpack-nano webpack-plugin-serve --save-dev

Note: We recommend using webpack-nano, a very tiny, very clean webpack CLI.

Usage

Create a webpack.config.js file:

const { WebpackPluginServe: Serve } = require('webpack-plugin-serve');
const options = { ... };

module.exports = {
	// an example entry definition
	entry: [
		'webpack-plugin-serve/client' // ← important: this is required, where the magic happens in the browser
		'app.js'
	]
  ...
  plugins: [
    new Serve(options)
  ],
  watch: true  // ← important: webpack and the server will continue to run in watch mode
};

Note: For more information and examples on configuring the entry property, please see the Configuring Entry Points recipe.

And run webpack:

$ npx wp
...
⬡ wps: Server Listening on: http://[::]:55555
...

Options

client

Type: Object
Default: null

Sets options specifically for the client script. In most situations this option doesn't need to be modified.

Properties

client.address

Type: String

If set, allows for overriding the WebSocket address, which corresponds to the server address by default. Values for this option should be in a valid {host}:{port} format. e.g. localhost:433.

client.protocol

Type: String

If set, allows for overriding the WebSocket protocol scheme string, which corresponds to the server protocol scheme by default. Values for this option should be one of the following: ws or wss.

client.retry

Type: Boolean

If true, instructs the client to attempt to reconnect all WebSockets when their connects are interrupted, usually as a result of the server being stopped and/or restarted. Note: This can be very spammy in the browser console, as there is no way to suppress error messages from the browser when a WebSocket fails to connect.

client.silent

Type: Boolean

If true, instructs the client not to log anything to the console.

compress

Type: Boolean
Default: false

If true, enables compression middleware which serves files with GZip compression.

historyFallback

Type: Boolean | Object
Default: false

If true, enables History API Fallback via connect-history-api-fallback. Users may also pass an options Object to this property. Please see connect-history-api-fallback for details.

This setting can be handy when using the HTML5 History API; index.html page will likely have to be served in place of any 404 responses from the server, specially when developing Single Page Applications.

Note: The Accept header is explicitly stripped from the /wps WebSocket path when using historyFallback, due to an issue with how Firefox and the middleware interact.

hmr

Type: boolean | 'refresh-on-failure'
Default: true

If true, will enable Hot Module Replacement which exchanges, adds, or removes modules from a bundle dynamically while the application still running, without the need of a full page reload.

Note: If the build process generates errors, the client (browser) will not be notified of new changes and no HMR will be performed. Errors must be resolved before HMR can proceed. To force a refresh, pass `refresh-on-failure' to this option.

Note: If using in combination with http2, the http2 option allowHTTP1 must be enabled for the HMR WS connection to work.

host

Type: String | Promise
Default: :: for IPv6, 127.0.0.1 for IPv4

Sets the host the server should listen from. Users may choose to set this to a Promise, or a Function which returns a Promise for situations in which the server needs to wait for a host to resolve.

Note: The default URI is http://[::]:{port}. For more info, please read the FAQ.

http2

Type: boolean | http2 options | secure http2 options

If set, this option will instruct the server to enable HTTP2. Properties for this option should correspond to HTTP2 options or HTTP2 SSL options.

Note: If using in combination with hmr, the option allowHTTP1 must be enabled for the HMR WS connection to work.

https

Type: Object
Default: null

If set, this option will instruct the server to enable SSL via HTTPS. Properties for this option should correspond to HTTPS options.

liveReload

Type: boolean
Default: false

If true, will instruct the client to perform a full page reload after each build.

Note: This option overrides any value set for the hmr option property.

log

Type: Object
Default: { level: 'info' }
Valid level Values: 'trace' | 'debug' | 'info' | 'warn' | 'error'

Sets a level for which messages should appear in the console. For example: if warn is set, every message at the warn and error levels will be visible. This module doesn't produce much log output, so you probably won't have to fiddle with this.

A timestamp: true property/value may also be used to preface each log line with an HH:mm:ss format timestamp.

middleware

Type: Function
Default: (app, builtins) => {}

Allows users to implement custom middleware, and manipulate the order in which built-in middleware is executed. This method may also return a Promise to pause further middleware evaluation until the Promise resolves. This property should only be set by users with solid knowledge of Express/Koa style middleware and those which understand the consequences of manipulating the order of built-in middleware.

Example

// webpack.config.js
module.exports = {
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) =>
        app.use(async (ctx, next) => {
          ctx.body = 'Hello world';
          await next();
        })
    })
  ]
};

Built-in Middleware

The builtins parameter provides access to all of the underlying middleware that the plugin uses internally. That provides users with a maximum amount of control over behavior of the server. For more information and examples of use, please see the Built-in Middleware recipe.

open

Type: boolean | Object
Default: false

If true, opens the default browser to the set host and port. Users may also choose to pass an Object containing options for the open module, which is used for this feature.

port

Type: Number | Promise
Default: 55555

Sets the port on which the server should listen. Users may choose to set this to a Promise, or a Function which returns a Promise for situations in which the server needs to wait for a port to resolve.

progress

Type: boolean | String
Default: true

If truthy, the module will add a ProgressPlugin instance to the webpack compiler, and display a progress indicator on the page within the browser.

If a value of 'minimal' is set, the progress indicator will render as a small, colored bar at the top of the window. This can be useful when the default fancy progress indicator interferes with elements in the page.

publicPath

Type: String
Default: webpack.output.publicPath

Sets the publicPath that the server should use to serve assets. You probably only need to set this explicitly if you are using Webpack's auto feature for public path detection.

ramdisk

Type: boolean | Object
Default: false
Support: MacOS and Linux, Windows with WSL 2.0.

If true or Object (options), will apply webpack-plugin-ramdisk to the build. output configuration does not have to be modified, a symlink will be created from the original output path to the output path on the ramdisk. Note: This will remove an existing directory at the defined output path.

Leveraging this option can result in significant reduction of build time, which is especially useful when using hmr: true or liveReload: true. Typical build times can be cut by 25-32% or more depending on hardware and webpack configuration. This is also recommended for users with SSD, as it reduces hard disk thrashing.

Windows users without WSL 2.0 are encouraged to install it to make use of this feature, or create a ramdisk manually using a tool like ImDisk.

static

Type: String | Array(String) | Object
Default: compiler.context

Sets the directory(s) from which static files will be served from the root of the application. Bundles will be served from the output config setting. For specifying options for static file directories, please see koa-static. For an in-depth example, check out the Static HTML File recipe.

The static option supports glob patterns when an Object is passed with a glob property. This is useful for targeting only specific directories in a complex tree. Users may also provide an options property which supports globby options. For example:

static: {
  glob: [path.join(__dirname, 'dist/**/public')],
  options: { onlyDirectories: true }
}

status

Type: boolean
Default: true

By default, webpack-plugin-serve will display a status overlay when a build results in errors and/or warnings. To disable this feature, set status: false in the options.

status overlay

When the minimize button (yellow dot) is clicked, the overlay will shrink to a single small box in the lower right corner of the page and display a status beacon using the same green, red, and yellow colors for build success, errors, and warnings, respectively.

status beacons

waitForBuild

Type: boolean
Default: false

If true, instructs the server to halt middleware processing until the current build is done.

Proxying

Proxying with webpack-plugin-serve is supported via the middleware option, specifically the proxy built-in. But while this plugin module doesn't contain any fancy options processing for proxying, it does include access to the http-proxy-middleware module by default, and the rest should look familiar to users of http-proxy-middleware.

// webpack.config.js
module.exports = {
  ...,
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) => {
        app.use(builtins.proxy('/api', { target: 'http://10.10.10.1:1337' }));
      }
    })
  ]
};

Note: The app.use(...) call here is slightly different than what Express users are used to seeing with http-proxy-middleware. This is due to subtle differences in how the module interacts with Koa, which is used under the hood in this plugin.

TypeScript Types

To get type definitions for this project:

npm install -D @types/webpack-plugin-serve

Meta

CONTRIBUTING

LICENSE (Mozilla Public License)

More Repositories

1

webpack-manifest-plugin

webpack plugin for generating asset manifests
JavaScript
1,433
star
2

jsx-email

Build emails with a delightful DX
TypeScript
924
star
3

koa-webpack

Development and Hot Reload Middleware for Koa2
JavaScript
441
star
4

webpack-nano

A teensy, squeaky 🐤 clean Webpack CLI
JavaScript
237
star
5

gmail-classic

CSS for reverting Gmail to the Classic Theme
CSS
216
star
6

postcss-less

PostCSS Syntax for parsing LESS
JavaScript
123
star
7

webpack-plugin-ramdisk

🐏 A webpack plugin for blazing fast builds on a RAM disk / drive
JavaScript
118
star
8

Gmail-Notifier-Plus

Gmail Notifier Plus
C#
89
star
9

prettier-plugin-package

An opinionated package.json formatter plugin for Prettier
JavaScript
81
star
10

mocha-chrome

☕ Run Mocha tests using headless Google Chrome
JavaScript
72
star
11

apollo-log

A logging extension for the Apollo GraphQL Server
TypeScript
66
star
12

postcss-values-parser

A CSS property value parser for PostCSS
JavaScript
58
star
13

webpack-serve

A CLI for webpack-plugin-serve, providing a premier webpack development server
JavaScript
51
star
14

loglevelnext

A modern logging library for Node.js that provides log level mapping to the console
TypeScript
38
star
15

OctoGerrit

A modern, clean, and usable theme for Gerrit
CSS
29
star
16

koa-ws

Empower your koa.js application with realtime
JavaScript
26
star
17

nanoid-cli

A tiny cli wrapper for nanoid
JavaScript
24
star
18

LiberaManifesto

A Manifesto for Open Source Software and Free Services
HTML
20
star
19

webpack-log

A logger for the Webpack ecosystem
JavaScript
18
star
20

doiuse-email

Lint HTML and CSS for email support against the `Can I email?` database.
TypeScript
14
star
21

Snarf

Snarf is an NFS server implementation written in C# with .NET 4.5.
C#
13
star
22

Brew

Brew is an open source library of interface components for ASP.NET which utilitizes jQuery and jQuery UI.
JavaScript
10
star
23

github-notifications-classic

A CSS project that restores the classic Github Notifications appearance.
CSS
9
star
24

Shellscape.Common

A .NET Library I use in a lot of my projects. Written in C#
C#
7
star
25

harmonica

A module that allows use of Node.js --harmony flags, programmatically.
JavaScript
7
star
26

webpack-hot-client

A client for enabling, and interacting with, webpack Hot Module Replacement
JavaScript
7
star
27

bundler-serve

A Platform for Bundler Development Servers
JavaScript
6
star
28

fwv

A ⚡️ crazy fast streaming ⚡️ Fixed Width Value Parser
JavaScript
5
star
29

gulp-scan

A Gulp plugin to scan a file for a particular string or expression
JavaScript
5
star
30

piilist

A list of Personally Identifiable Information keys / words / phrases used for redaction or removal
JavaScript
3
star
31

thank-you

A place for me to thank the outstanding people who support my work
3
star
32

Lumen

Everything that Start should have been.
C#
3
star
33

dot

Tools for monorepos, serverless, and more
TypeScript
2
star
34

shellscape.github.io

The codebase for shellscape.org
HTML
2
star
35

Gcal-Notifier-Plus

A Google Calendar Notifier for Windows 7
C#
2
star
36

gulp-assist

Display helpful information for your Gulp tasks
JavaScript
2
star
37

babel-plugin-async-to-plain-generator

Transform async functions into non-wrapped ES2015 generators
JavaScript
2
star
38

npm-version-tree

Fetch a dependency version tree for a package
JavaScript
2
star
39

Nubs

Fancy Tabs for the Windows Desktop
C#
1
star
40

travis-target

A Node.js module to determine the file or directory targets of a Travis CI build.
JavaScript
1
star
41

gulp-mocha-chrome

☕ Run Mocha tests using Google Chrome via Gulp
JavaScript
1
star
42

prettier-tree

Prettier directory trees
1
star
43

Rumshot

1
star
44

eslint-config-shellscape

ESLint shareable config for my projects
JavaScript
1
star
45

gulp-version-conflicts

Check for and report on module version conflicts for a package
JavaScript
1
star