• This repository has been archived on 08/Apr/2019
  • Stars
    star
    1,095
  • Rank 40,613 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 5 years ago

Reviews

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

Repository Details

Repository has moved:

npm node deps tests coverage chat size

webpack-serve

DEPRECATED. Please use webpack-dev-server (he is in support and update mode again). Feel free to create a issue if some features are not implemented in webpack-dev-server.

Why deprecated webpack-serve ?

Thanks for using webpack! We apologize for the inconvenience. In the future, we will avoid such situations.

Use gitter and/or slack if you have questions.


A lean, modern, and flexible webpack development server

Requirements

This module requires a minimum of Node.js v6.9.0 and Webpack v4.0.0.

Browser Support

Because this module leverages native WebSockets via webpack-hot-client, the browser support for this module is limited to only those browsers which support native WebSocket. That typically means the last two major versions of a particular browser. You may view a table of compatible browsers here.

Note: We won't be accepting requests for changes to this facet of the module.

Getting Started

To begin, you'll need to install webpack-serve:

$ npm install webpack-serve --save-dev

CLI

$ webpack-serve --help

A lean, modern, and flexible webpack development server

Usage
  $ webpack-serve <config> [...options]

Options
  --clipboard      Specify whether or not the server should copy the server URI to the clipboard (default: true)
  --config         The webpack config to serve. Alias for <config>
  --content        The path from which static content will be served (default: process.cwd)
  --dev-ware       Set options for webpack-dev-middleware. e.g. --dev-ware.publicPath /
  --help           Show usage information and the options listed here.
  --host           The host the app should bind to
  --hot-client     Set options for webpack-hot-client. e.g. --hot-client.host localhost
                   Use --no-hot-client to disable webpack-hot-client
  --http2          Instruct the server to use HTTP2
  --https-cert     Specify a filesystem path of an SSL certificate. Must be paired with a key
  --https-key      Specify a filesystem path of an SSL key. Must be paired with a cert
  --https-pass     Specify a passphrase to enable https. Must be paired with a pfx file
  --https-pfx      Specify a filesystem path of an SSL pfx file. Must be paired with a passphrase
  --log-level      Limit all process console messages to a specific level and above
                   Levels: trace, debug, info, warn, error, silent
  --log-time       Instruct the logger for webpack-serve and dependencies to display a timestamp
  --hmr            Specify whether or not the client should apply Hot Module Replacement patches (default: true)
  --reload         Specify whether or not the middleware should reload the page for build errors (default: true)
  --open           Instruct the app to open in the default browser
  --open-app       The name of the app to open the app within, or an array
                   containing the app name and arguments for the app
  --open-path      The path with the app a browser should open to
  --port           The port the app should listen on. Default: 8080
  --require, -r    Preload one or more modules before loading the webpack configuration
  --version        Display the webpack-serve version

Note: Any boolean flag can be prefixed with 'no-' instead of specifying a value.
e.g. --no-reload rather than --reload=false

Examples
  $ webpack-serve ./webpack.config.js --no-reload
  $ webpack-serve --config ./webpack.config.js --port 1337
  $ webpack-serve # config can be omitted for webpack v4+ only

Note: The CLI will use your local install of webpack-serve when available, even when run globally.

Running the CLI

There are a few variations for using the base CLI command, and starting webpack-serve:

$ webpack-serve ./webpack.config.js
$ webpack-serve --config ./webpack.config.js

Those two commands are synonymous. Both instruct webpack-serve to load the config from the specified path. We left the flag in there because some folks like to be verbose, so why not.

$ webpack-serve

You may also instruct webpack-serve to kick off a webpack build without specifying a config. This will apply the zero-config defaults within webpack, and your project must conform to that for a successful build to happen.

webpack-serve Config

You can store and define configuration / options for webpack-serve in a number of different ways. This module leverages cosmiconfig, which allows you to define webpack-serve options in the following ways:

  • in your package.json file in a serve property
  • in a .serverc or .serverc.json file, in either JSON or YML.
  • in a serve.config.js file which exports a CommonJS module (just like webpack).

It's most common to keep serve options in your webpack.config.js (see below), however, you can utilize any of the options above in tandem with webpack.config.js, and the options from the two sources will be merged. This can be useful for setups with multiple configs that share common options for webpack-serve, but require subtle differences.

webpack.config.js Example

const path = require('path');

module.exports = {
  context: __dirname,
  devtool: 'source-map',
  entry: ['./app.js'],
  output: {
    filename: './output.js',
    path: path.resolve(__dirname),
  },
  serve: {},
};

Webpack Config serve Property

webpack-serve supports the serve property in your webpack config file, which may contain any of the supported options.

Setting the Config mode

Should you find that the mode property of your webpack config file needs to be set dynamically the following pattern can be used:

mode: process.env.WEBPACK_SERVE ? 'development' : 'production',

API

When using the API directly, the main entry point is the serve function, which is the default export of the module.

const serve = require('webpack-serve');
const argv = {};
const config = require('./webpack.config.js');

serve(argv, { config }).then((result) => {
  // ...
});

serve(argv, options)

Returns: Promise
Resolves: <Object> result

result.app

Type: Koa

An instance of a Koa application, extended with a server property, and stop method, which is used to programatically stop the server.

result.on

Type: Function

A function which binds a serve event-name to a function. See Events.

result.options

Type: Object

Access to a frozen copy of the internal options object used by the module.

argv

Type: Object
Required

An object containing the parsed result from either minimist or yargs-parser.

options

Type: Object
Required

An object specifying options used to configure the server.

options.add

Please see Add-On Features.

options.compiler

Type: webpack
Default: null

An instance of a webpack compiler. A passed compiler's config will take precedence over config passed in options.

Note: Any serve configuration must be removed from the webpack config used to create the compiler instance, before you attempt to create it, as it's not a valid webpack config property.

options.config

Type: Object
Default: {}

An object containing the configuration for creating a new webpack compiler instance.

options.content

Type: String|[String]
Default: process.cwd()

The path, or array of paths, from which content will be served. Paths specified here should be absolute, or fully-qualified and resolvable by the filesystem.

Note: By default the files generated by webpack take precedence over static files served from content paths.

To instruct the server to give static files precedence, use the add option, and call middleware.content() before middleware.webpack():

add: (app, middleware, options) => {
  middleware.content();
  middleware.webpack();
};

Read more about the add option in Add-On Features.

options.clipboard

Type: Boolean
Default: true

If true, the server will copy the server URI to the clipboard when the server is started.

options.devMiddleware

Type: Object
Default: { publicPath: '/' }

An object containing options for webpack-dev-middleware.

options.host

Type: String
Default: 'localhost'

Sets the host that the server will listen on. eg. '10.10.10.1'

Note: This value must match any value specified for hot.host or hot.host.server, otherwise webpack-serve will throw an error. This requirement ensures that the koa server and WebSocket server play nice together.

options.hotClient

Type: Object|Boolean
Default: {}

An object containing options for webpack-hot-client. Setting this to false will completely disable webpack-hot-client and all automatic Hot Module Replacement functionality.

options.http2

Type: Boolean
Default: false

If using Node v9 or greater, setting this option to true will enable HTTP2 support.

options.https

Type: Object
Default: null

Passing this option will instruct webpack-serve to create and serve the webpack bundle and accompanying content through a secure server. The object should contain properties matching:

{
  key: fs.readFileSync('...key'),   // Private keys in PEM format.
  cert: fs.readFileSync('...cert'), // Cert chains in PEM format.
  pfx: <String>,                    // PFX or PKCS12 encoded private key and certificate chain.
  passphrase: <String>              // A shared passphrase used for a single private key and/or a PFX.
}

See the Node documentation for more information. For SSL Certificate generation, please read the SSL Certificates for HTTPS section.

options.logLevel

Type: String
Default: info

Instructs webpack-serve to output information to the console/terminal at levels higher than the specified level. Valid levels:

[
  'trace',
  'debug',
  'info',
  'warn',
  'error',
  'silent'
]

options.logTime

Type: Boolean
Default: false

Instruct webpack-serve to prepend each line of log output with a [HH:mm:ss] timestamp.

options.on

Type: Object
Default: null

While running webpack-serve from the command line, it can sometimes be useful to subscribe to events from the module's event bus within your config. This option can be used for that purpose. The option's value must be an Object matching a key:handler, String: Function pattern. eg:

on: {
  'build-started': () => { console.log('build started!'); }
}

open

Type: Boolean|Object
Default: false

Instruct the module to open the served bundle in a browser. Accepts an Object that matches:

{
  app: <String>, // The proper name of the browser app to open.
  path: <String> // The url path on the server to open.
}

Note: Using the open option will disable the clipboard option.

port

Type: Number
Default: 8080

The port the server should listen on.

Events

The server created by webpack-serve emits select events which can be subscribed to. All events are emitted with a single Object parameter, containing named properties for relevant data.

For example:

const serve = require('webpack-serve');
const argv = {};
const config = require('./webpack.config.js');

serve(argv, { config }).then((server) => {
  server.on('listening', ({ server, options }) => {
    console.log('happy fun time');
  });
});

build-started

Arguments:
 Compiler compiler

Emitted when a compiler has started a build.

build-finished

Arguments:
 Stats stats
 Compiler compiler

Emitted when a compiler has finished a build.

compiler-error

Arguments:
 Stats json
 Compiler compiler

Emitted when a compiler has encountered and error, or a build has errors.

compiler-warning

Arguments:
 Stats json
 Compiler compiler

Emitted when a compiler has encountered a warning, or a build has warnings.

listening

Arguments:
 net.Server
 Object options

Emitted when the server begins listening for connections.

SSL Certificates for HTTPS

Unlike webpack-dev-server, webpack-serve does not ship with SSL Certificate generation, nor does it ship with a built-in certificate for use with HTTPS configurations. This is due largely in part to past security concerns and the complexity of use-cases in the webpack ecosystem.

We do however, recommend a path for users to generate their own SSL Certificates safely and efficiently. That path resides in devcert-cli; an excellent project that automates the creation of trusted SSL certificates that will work wonderfully with webpack-serve.

Add-on Features

A core tenet of webpack-serve is to stay lean in terms of feature set, and to empower users with familiar and easily portable patterns to implement the same features that those familiar with webpack-dev-server have come to rely on. This makes the module far easier to maintain, which ultimately benefits the user.

Luckily, flexibility baked into webpack-serve makes it a snap to add-on features. You can leverage this by using the add option. The value of the option should be a Function matching the following signature:

add: (app, middleware, options) => {
  // ...
}

add Function Parameters

  • app The underlying Koa app
  • middleware An object containing accessor functions to call both webpack-dev-middleware and the koa-static middleware.
  • options - The internal options object used by webpack-serve

Some add-on patterns may require changing the order of middleware used in the app. For instance, if adding routes or using a separate router with the app where routes must be added last, you'll need to call the middleware functions early on. webpack-serve recognizes these calls and will not execute them again. If these calls were omitted, webpack-serve would execute both in the default, last in line, order.

add: (app, middleware, options) => {
  // since we're manipulating the order of middleware added, we need to handle
  // adding these two internal middleware functions.
  middleware.webpack();
  middleware.content();

  // router *must* be the last middleware added
  app.use(router.routes());
}

Listed below are some of the add-on patterns and recipes that can be found in docs/addons:

Community Add-ons

Note: The list below contains webpack-serve add-ons created by the community. Inclusion in the list does not imply a module is preferred or recommended over others.

Contributing

We welcome your contributions! Please take a moment to read our contributing guidelines if you haven't yet done so.

License

More Repositories

1

webpack-bundle-analyzer

Webpack plugin and CLI utility that represents bundle content as convenient interactive zoomable treemap
JavaScript
12,483
star
2

mini-css-extract-plugin

Lightweight CSS extraction plugin
JavaScript
4,621
star
3

awesome-webpack

A curated list of awesome Webpack resources, libraries and tools
HTML
4,566
star
4

css-loader

CSS Loader
JavaScript
4,274
star
5

extract-text-webpack-plugin

[DEPRECATED] Please use https://github.com/webpack-contrib/mini-css-extract-plugin Extracts text from a bundle into a separate file
JavaScript
4,020
star
6

sass-loader

Compiles Sass to CSS
JavaScript
3,890
star
7

postcss-loader

PostCSS loader for webpack
JavaScript
2,845
star
8

copy-webpack-plugin

Copy files and directories with webpack
JavaScript
2,820
star
9

webpack-hot-middleware

Webpack hot reloading you can attach to your own server
JavaScript
2,335
star
10

terser-webpack-plugin

Terser Plugin
JavaScript
1,924
star
11

file-loader

File Loader
JavaScript
1,866
star
12

style-loader

Style Loader
JavaScript
1,642
star
13

worker-loader

A webpack loader that registers a script as a Web Worker
JavaScript
1,448
star
14

install-webpack-plugin

Speed up development by automatically installing & saving dependencies with Webpack.
JavaScript
1,435
star
15

url-loader

A loader for webpack which transforms files into base64 URIs
JavaScript
1,407
star
16

compression-webpack-plugin

Prepare compressed versions of assets to serve them with Content-Encoding
JavaScript
1,400
star
17

uglifyjs-webpack-plugin

[deprecated] UglifyJS Plugin
JavaScript
1,382
star
18

html-loader

HTML Loader
JavaScript
1,161
star
19

thread-loader

Runs the following loaders in a worker pool
JavaScript
1,114
star
20

eslint-loader

[DEPRECATED] A ESlint loader for webpack
JavaScript
1,058
star
21

less-loader

Compiles Less to CSS
JavaScript
952
star
22

raw-loader

A loader for webpack that allows importing files as a String
JavaScript
846
star
23

purifycss-webpack

UNMAINTAINED, use https://github.com/FullHuman/purgecss-webpack-plugin
JavaScript
773
star
24

bundle-loader

Bundle Loader
JavaScript
662
star
25

cache-loader

[DEPRECATED] Caches the result of following loaders on disk
JavaScript
641
star
26

expose-loader

Expose Loader
JavaScript
545
star
27

imports-loader

Imports Loader
JavaScript
520
star
28

stylus-loader

🎨 A stylus loader for webpack.
JavaScript
498
star
29

babel-minify-webpack-plugin

[DEPRECATED] Babel Minify Webpack Plugin
JavaScript
493
star
30

svg-inline-loader

Inline SVG loader with cleaning-up functionality
JavaScript
490
star
31

json-loader

json loader module for webpack - UNMAINTAINED
JavaScript
438
star
32

closure-webpack-plugin

Webpack Google Closure Compiler and Closure Library plugin -
JavaScript
434
star
33

stylelint-webpack-plugin

A Stylelint plugin for webpack
JavaScript
425
star
34

source-map-loader

extract sourceMappingURL comments from modules and offer it to webpack
JavaScript
355
star
35

script-loader

[deprecated] Script Loader
JavaScript
325
star
36

i18n-webpack-plugin

[DEPRECATED] Embed localization into your bundle
JavaScript
318
star
37

css-minimizer-webpack-plugin

cssnano plugin for Webpack
JavaScript
305
star
38

istanbul-instrumenter-loader

Istanbul Instrumenter Loader
JavaScript
273
star
39

grunt-webpack

integrate webpack into grunt build process
JavaScript
266
star
40

react-proxy-loader

Wraps a react component in a proxy component to enable Code Splitting.
JavaScript
259
star
41

eslint-webpack-plugin

A ESLint plugin for webpack
JavaScript
250
star
42

image-minimizer-webpack-plugin

Webpack loader and plugin to compress images using imagemin
JavaScript
220
star
43

exports-loader

Exports Loader
JavaScript
214
star
44

webpack-command

[DEPRECATED] Lightweight, modular, and opinionated webpack CLI that provides a superior experience
JavaScript
213
star
45

webpack-stylish

A stylish, optionated reporter for webpack
JavaScript
202
star
46

val-loader

val loader module for webpack
JavaScript
181
star
47

mocha-loader

Mocha Loader
JavaScript
147
star
48

null-loader

[DEPRECATED] A loader that returns an empty module (can still be used for webpack 4).
JavaScript
144
star
49

coffee-loader

CoffeeScript Loader
JavaScript
142
star
50

webpack-hot-client

webpack HMR Client
JavaScript
120
star
51

node-loader

node loader for native modules
JavaScript
116
star
52

transform-loader

transform loader for webpack
JavaScript
110
star
53

webpack-defaults

Defaults to be shared across webpack projects
JavaScript
108
star
54

json5-loader

[Deprecated] JSON5 loader for Webpack (can still be used for webpack 4)
JavaScript
72
star
55

jshint-loader

[DEPRECATED] jshint loader for webpack, please migrate on `eslint`
JavaScript
67
star
56

webpack-canary

Canary tooling for checking webpack dependencies against specific webpack versions
JavaScript
47
star
57

multi-loader

[DEPRECATED] A loader that splits a module into multiple modules loaded with different loaders.
JavaScript
44
star
58

webpack-log

[DEPRECATED] Please use logger API https://github.com/webpack/webpack/pull/9436
JavaScript
38
star
59

zopfli-webpack-plugin

[DEPRECATED] Prepare compressed versions of assets with node-zopfli
JavaScript
26
star
60

component-webpack-plugin

Use components with webpack - UNMAINTAINED
JavaScript
20
star
61

remark-loader

Load markdown through remark with image resolving and some react-specific features.
JavaScript
15
star
62

gzip-loader

[DEPRECATED] gzip loader module for webpack
JavaScript
15
star
63

yaml-frontmatter-loader

[DEPRECATED] Yaml frontmatter loader
JavaScript
14
star
64

json-minimizer-webpack-plugin

JSON minimizer webpack plugin
JavaScript
14
star
65

config-loader

[DEPRECATED] A loader for webpack configuration files
JavaScript
14
star
66

html-minimizer-webpack-plugin

HTML minimizer webpack plugin
JavaScript
13
star
67

organization

Applications, Standards & Documentation for webpack-contrib.
13
star
68

i18n-loader

i18n loader module for webpack - UNMAINTAINED
JavaScript
11
star
69

eslint-config-webpack

Webpack standard eslint configuration
JavaScript
9
star
70

coffee-redux-loader

coffee redux loader module for webpack - UNMAINTAINED
JavaScript
7
star
71

test-utils

webpack Loader/Plugin Test Helpers
JavaScript
6
star
72

coverjs-loader

coverjs loader module for webpack - UNMAINTAINED
JavaScript
4
star
73

circleci-node8

[DEPRECATED] Please migrate on azure pipelines. CircleCI 2.0 NodeJS 8 build container -
Dockerfile
3
star
74

restyle-loader

[DEPRECATED] Use https://github.com/danielverejan/restyle-loader
JavaScript
3
star
75

tag-versions

A commandline wrapper around omichelsen/compare-versions to compare dist-tags
JavaScript
2
star
76

circleci-node-base

CircleCI 2.0 base build container -
Dockerfile
1
star
77

babel-preset-webpack

[DEPRECATED] Webpack Organization es2015 Babel Preset - See:
JavaScript
1
star
78

circleci-node9

[DEPRECATED] Please migrate on azure pipelines. CircleCI 2.0 NodeJS 9 build container -
Dockerfile
1
star
79

circleci-node-jdk8

Deprecated, use ->
1
star
80

cli-utils

[DEPRECATED] A suite of utilities for webpack projects which expose a CLI
JavaScript
1
star