Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: webpack/webpack-dev-server
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: bf741ce8143dc61e3e946536d1b1b42d3ed16355
Choose a base ref
...
head repository: webpack/webpack-dev-server
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 298341f0757e871896c1a7a27983d15f977fb209
Choose a head ref

Commits on Oct 17, 2015

  1. 6
    Copy the full SHA
    2e3ac57 View commit details
  2. Copy the full SHA
    4944529 View commit details

Commits on Jan 20, 2016

  1. updated optimist to yargs

    sokra committed Jan 20, 2016
    Copy the full SHA
    802dd7c View commit details
  2. Merge branch 'web-worker-hmr' of https://github.com/elliottsj/webpack…

    …-dev-server into elliottsj-web-worker-hmr
    
    # Conflicts:
    #	client/index.js
    sokra committed Jan 20, 2016
    Copy the full SHA
    6e75a44 View commit details
  3. Copy the full SHA
    7e2e8f8 View commit details
  4. config stuff

    sokra committed Jan 20, 2016
    Copy the full SHA
    2a80e33 View commit details

Commits on Jan 21, 2016

  1. Inline mode is on by default

    sokra committed Jan 21, 2016
    Copy the full SHA
    5b94506 View commit details
  2. Prevent application from covering up webpack errors

    Currently, my web application is getting rendered on top of the build errors/warnings, preventing me from seeing them. This CSS change seems to fix it.
    BHSPitMonkey committed Jan 21, 2016
    1
    Copy the full SHA
    4fda020 View commit details
  3. 2.0.0-beta

    sokra committed Jan 21, 2016
    Copy the full SHA
    3dd3e2a View commit details

Commits on Jan 26, 2016

  1. Copy the full SHA
    e5f698d View commit details

Commits on Jan 29, 2016

  1. correct proxy options

    qpias committed Jan 29, 2016
    Copy the full SHA
    ed43efa View commit details

Commits on Feb 24, 2016

  1. Permit newer (properly versioned) webpack@2 betas

    Nicholas Kinsey committed Feb 24, 2016
    Copy the full SHA
    2021657 View commit details

Commits on Mar 3, 2016

  1. Copy the full SHA
    0f4bc2d View commit details
  2. Copy the full SHA
    35286d8 View commit details

Commits on Mar 16, 2016

  1. Copy the full SHA
    d7d0741 View commit details

Commits on Mar 24, 2016

  1. Copy the full SHA
    be7d268 View commit details
  2. Merge pull request #436 from Smotko/update-ssl-certificates

    Update self signed ssl certificates
    sokra committed Mar 24, 2016
    Copy the full SHA
    7df2812 View commit details
  3. Merge pull request #430 from pcorpet/allow-variable-port

    Guess server's port from current page.
    sokra committed Mar 24, 2016
    Copy the full SHA
    e5df542 View commit details
  4. Merge pull request #419 from crohde7707/master

    Update webpack-dev-server to accept a promise
    sokra committed Mar 24, 2016
    Copy the full SHA
    5269e76 View commit details
  5. Merge pull request #412 from pyrotechnick/patch-3

    Permit newer (properly versioned) webpack@2 betas
    sokra committed Mar 24, 2016
    Copy the full SHA
    d532031 View commit details
  6. fixes webpack-dev-server#403 and webpack-dev-server#402 and updates d…

    …ev dependencies to use webpack 2 only
    KarlAmort authored and sokra committed Mar 24, 2016
    Copy the full SHA
    0d150e9 View commit details
  7. fix webpack dependency in package.json

    KarlAmort authored and sokra committed Mar 24, 2016
    Copy the full SHA
    4d083a7 View commit details
  8. Copy the full SHA
    831fa4b View commit details
  9. Copy the full SHA
    9356b65 View commit details
  10. Merge pull request #392 from qpias/master

    correct proxy options
    sokra committed Mar 24, 2016
    Copy the full SHA
    8442a83 View commit details

Commits on Mar 25, 2016

  1. Merge pull request #385 from dickeylth/master

    add `staticOptions` for expose express.static options pass in
    sokra committed Mar 25, 2016
    Copy the full SHA
    fcd7b7e View commit details
  2. Merge pull request #380 from BHSPitMonkey/patch-1

    Prevent application from covering up webpack errors
    sokra committed Mar 25, 2016
    Copy the full SHA
    2c9a461 View commit details

Commits on Apr 6, 2016

  1. Copy the full SHA
    924bd1b View commit details

Commits on Apr 12, 2016

  1. Copy the full SHA
    6dc80ec View commit details

Commits on Apr 30, 2016

  1. Copy the full SHA
    70bc376 View commit details

Commits on May 6, 2016

  1. Don't reload app upon proxy errors.

    Previously the clientside application would reload whenever a proxy answered with an error reponse
    or in other ways behaved badly. This change removes that reloading behavior, as reload the clientside
    application probably won't fix any issue the proxy has anyway.
    phillipj committed May 6, 2016
    1
    Copy the full SHA
    a233ecf View commit details

Commits on May 7, 2016

  1. FIX console.log spacing

    - There is open issue #365 for this earlier this year, with appropriate PR, but conflicts are preventing it from merge
    
    Closes #365
    sanusart committed May 7, 2016
    Copy the full SHA
    903c603 View commit details

Commits on May 15, 2016

  1. Merge pull request #447 from svsool/bug

    fix bug when src attribute not defined on last script element
    Merging this in favor of #394
    jhnns committed May 15, 2016
    Copy the full SHA
    4ecbae6 View commit details
  2. Merge pull request #478 from phillipj/patch-1

    Don't reload app upon proxy errors.
    sokra committed May 15, 2016
    Copy the full SHA
    873d834 View commit details
  3. Merge pull request #470 from nightwing/patch-1

    Allow running dev-server behind https proxy
    sokra committed May 15, 2016
    Copy the full SHA
    7fc08e8 View commit details
  4. Merge pull request #469 from sanusart/master

    FIX console.log spacing
    sokra committed May 15, 2016
    Copy the full SHA
    76a51d5 View commit details
  5. merged #443

    sokra committed May 15, 2016
    Copy the full SHA
    991f2aa View commit details
  6. Merge pull request #439 from SimenB/hot-only

    Add hot-only option to allow setting `only-dev-server` from cli or config
    sokra committed May 15, 2016
    Copy the full SHA
    a77eac5 View commit details
  7. updated dependencies

    sokra committed May 15, 2016
    Copy the full SHA
    9baae0a View commit details
  8. 2.1.0-beta.0

    sokra committed May 15, 2016
    Copy the full SHA
    dd61b99 View commit details

Commits on Jun 6, 2016

  1. Copy the full SHA
    0cf7830 View commit details
  2. Merge pull request #499 from BROCKHAUS-AG/master

    set headers on all methods to support e.g. CORS
    sokra committed Jun 6, 2016
    Copy the full SHA
    2f02d0c View commit details

Commits on Jun 14, 2016

  1. Return http.Server instance from listen

    Return the `http.Server` instance from `listen` to [match the return value of the same function in express](https://github.com/expressjs/express/blob/31dd549f350accd7b4e3685c13f745e857557827/lib/application.js#L617).
    mjackson authored Jun 14, 2016
    Copy the full SHA
    48e41f1 View commit details

Commits on Jul 21, 2016

  1. Copy the full SHA
    f27f1c2 View commit details

Commits on Jul 25, 2016

  1. pass this to setup. Fixes #536

    graingert authored Jul 25, 2016
    Copy the full SHA
    ddb2b1f View commit details

Commits on Aug 21, 2016

  1. Merge pull request #537 from graingert/patch-1

    pass `this` to setup. Fixes #536
    SpaceK33z authored Aug 21, 2016
    Copy the full SHA
    87ddebd View commit details
  2. Merge pull request #532 from ryan-codingintrigue/master

    Assign --cacert CLI argument to correct server options property
    SpaceK33z authored Aug 21, 2016
    Copy the full SHA
    d9266b9 View commit details
  3. Merge pull request #506 from mjackson/patch-3

    Return http.Server instance from listen
    SpaceK33z authored Aug 21, 2016
    Copy the full SHA
    f5d7912 View commit details
  4. Enable linting for some forgotten files

    And fix the lint errors.
    SpaceK33z committed Aug 21, 2016
    Copy the full SHA
    2eef9e6 View commit details
  5. Add goals to readme

    SpaceK33z committed Aug 21, 2016
    Copy the full SHA
    4946b25 View commit details
Showing with 17,291 additions and 1,111 deletions.
  1. +3 −0 .babelrc
  2. +12 −4 .editorconfig
  3. +1 −0 .eslintignore
  4. +17 −26 .eslintrc
  5. +1 −1 .gitattributes
  6. +53 −0 .github/ISSUE_TEMPLATE.md
  7. +36 −0 .github/PULL_REQUEST_TEMPLATE.md
  8. +6 −2 .gitignore
  9. +0 −25 .jsbeautifyrc
  10. +18 −3 .travis.yml
  11. +57 −0 CONTRIBUTING.md
  12. +20 −0 LICENSE
  13. +164 −9 README.md
  14. +442 −146 bin/webpack-dev-server.js
  15. +243 −0 client-src/default/index.js
  16. +129 −0 client-src/default/overlay.js
  17. +42 −0 client-src/default/socket.js
  18. +22 −0 client-src/default/webpack.config.js
  19. +124 −0 client-src/live/index.js
  20. 0 {client → client-src/live}/live.html
  21. 0 client/page.jade → client-src/live/page.pug
  22. 0 {client → client-src/live}/style.css
  23. 0 {client → client-src/live}/web_modules/jquery/index.js
  24. 0 {client → client-src/live}/web_modules/jquery/jquery-1.8.1.js
  25. +41 −0 client-src/live/webpack.config.js
  26. +3 −0 client-src/sockjs/index.js
  27. +14 −0 client-src/sockjs/webpack.config.js
  28. +0 −96 client/index.js
  29. +0 −128 client/live.js
  30. +0 −11 client/webpack.config.js
  31. +0 −66 example/README.md
  32. +0 −13 example/alternative.config.js
  33. +0 −9 example/app.js
  34. +0 −11 example/inlined.html
  35. +0 −1 example/unparseable.js
  36. +0 −29 example/webpack.config.array.js
  37. +0 −10 example/webpack.config.js
  38. BIN examples/.assets/favicon.ico
  39. BIN examples/.assets/geomanist-medium.woff
  40. BIN examples/.assets/geomanist-medium.woff2
  41. +1 −0 examples/.assets/icon-square.svg
  42. +26 −0 examples/.assets/layout.html
  43. +104 −0 examples/.assets/style.css
  44. +5 −0 examples/.eslintrc
  45. +29 −0 examples/README.md
  46. +20 −0 examples/api/middleware/README.md
  47. +6 −0 examples/api/middleware/app.js
  48. +23 −0 examples/api/middleware/server.js
  49. +13 −0 examples/api/middleware/webpack.config.js
  50. +17 −0 examples/api/simple/README.md
  51. +17 −0 examples/api/simple/app.js
  52. +17 −0 examples/api/simple/server.js
  53. +13 −0 examples/api/simple/webpack.config.js
  54. +15 −0 examples/cli/bonjour/README.md
  55. +5 −0 examples/cli/bonjour/app.js
  56. +10 −0 examples/cli/bonjour/webpack.config.js
  57. +25 −0 examples/cli/compression/README.md
  58. +6 −0 examples/cli/compression/app.js
  59. +10 −0 examples/cli/compression/webpack.config.js
  60. +25 −0 examples/cli/default/README.md
  61. +20 −0 examples/cli/default/app.js
  62. BIN {example → examples/cli/default}/pixels.png
  63. +1 −1 {example → examples/cli/default}/style.less
  64. +1 −1 {example → examples/cli/default}/svg.svg
  65. +27 −0 examples/cli/default/webpack.config.js
  66. +20 −0 examples/cli/history-api-fallback/README.md
  67. +75 −0 examples/cli/history-api-fallback/app.js
  68. +1 −0 examples/cli/history-api-fallback/file.txt
  69. +15 −0 examples/cli/history-api-fallback/webpack.config.js
  70. +30 −0 examples/cli/hmr/README.md
  71. +11 −0 examples/cli/hmr/app.js
  72. +5 −0 examples/cli/hmr/example.js
  73. +10 −0 examples/cli/hmr/webpack.config.js
  74. +24 −0 examples/cli/host-and-port/README.md
  75. +6 −0 examples/cli/host-and-port/app.js
  76. +10 −0 examples/cli/host-and-port/webpack.config.js
  77. +36 −0 examples/cli/https/README.md
  78. +6 −0 examples/cli/https/app.js
  79. BIN examples/cli/https/test_cert.pfx
  80. +10 −0 examples/cli/https/webpack.config.js
  81. +19 −0 examples/cli/iframe/README.md
  82. +12 −0 examples/cli/iframe/app.js
  83. +10 −0 examples/cli/iframe/webpack.config.js
  84. +19 −0 examples/cli/lazy/README.md
  85. +12 −0 examples/cli/lazy/app.js
  86. +10 −0 examples/cli/lazy/webpack.config.js
  87. +50 −0 examples/cli/listen-socket/README.md
  88. +6 −0 examples/cli/listen-socket/app.js
  89. +9 −0 examples/cli/listen-socket/check-socket.js
  90. +10 −0 examples/cli/listen-socket/webpack.config.js
  91. +10 −0 examples/cli/node-false/README.md
  92. +6 −0 examples/cli/node-false/app.js
  93. +11 −0 examples/cli/node-false/webpack.config.js
  94. +14 −0 examples/cli/open-page/README.md
  95. +11 −0 examples/cli/open-page/app.js
  96. +18 −0 examples/cli/open-page/webpack.config.js
  97. +18 −0 examples/cli/overlay/README.md
  98. +9 −0 examples/cli/overlay/app.js
  99. +10 −0 examples/cli/overlay/webpack.config.js
  100. +12 −0 examples/cli/progress/README.md
  101. +6 −0 examples/cli/progress/app.js
  102. +13 −0 examples/cli/progress/webpack.config.js
  103. +18 −0 examples/cli/public-protocol/README.md
  104. +5 −0 examples/cli/public-protocol/app.js
  105. +8 −0 examples/cli/public-protocol/index.html
  106. +15 −0 examples/cli/public-protocol/webpack.config.js
  107. +21 −0 examples/cli/public/README.md
  108. +6 −0 examples/cli/public/app.js
  109. +10 −0 examples/cli/public/webpack.config.js
  110. +16 −0 examples/cli/stdin/README.md
  111. +5 −0 examples/cli/stdin/app.js
  112. +6 −0 examples/cli/stdin/webpack.config.js
  113. +42 −0 examples/cli/watch-content-base/README.md
  114. +6 −0 examples/cli/watch-content-base/app.js
  115. +11 −0 examples/cli/watch-content-base/assets/index.html
  116. +3 −0 examples/cli/watch-content-base/css/styles.css
  117. +16 −0 examples/cli/watch-content-base/webpack.config.js
  118. +14 −0 examples/general/config-array/README.md
  119. +14 −0 examples/general/config-array/app.js
  120. BIN examples/general/config-array/pixels.png
  121. +3 −0 examples/general/config-array/style.less
  122. +33 −0 examples/general/config-array/svg.svg
  123. +57 −0 examples/general/config-array/webpack.config.js
  124. +13 −0 examples/general/config-promise/README.md
  125. +5 −0 examples/general/config-promise/app.js
  126. +2 −2 {example → examples/general/config-promise}/index.html
  127. +14 −0 examples/general/config-promise/webpack.config.js
  128. +19 −0 examples/general/proxy-advanced/README.md
  129. +6 −0 examples/general/proxy-advanced/app.js
  130. +8 −0 examples/general/proxy-advanced/bypass.html
  131. +26 −0 examples/general/proxy-advanced/webpack.config.js
  132. +36 −0 examples/general/proxy-hot-reload/README.md
  133. +6 −0 examples/general/proxy-hot-reload/app.js
  134. +20 −0 examples/general/proxy-hot-reload/proxy-config.js
  135. +45 −0 examples/general/proxy-hot-reload/webpack.config.js
  136. +16 −0 examples/general/proxy-simple/README.md
  137. +6 −0 examples/general/proxy-simple/app.js
  138. +15 −0 examples/general/proxy-simple/webpack.config.js
  139. +16 −0 examples/general/webworker/README.md
  140. +11 −0 examples/general/webworker/web.js
  141. +22 −0 examples/general/webworker/webpack.config.js
  142. +10 −0 examples/general/webworker/worker.js
  143. +76 −0 examples/util.js
  144. +152 −0 lib/OptionsValidationError.js
  145. +718 −392 lib/Server.js
  146. +336 −0 lib/optionsSchema.json
  147. +8 −0 lib/polyfills.js
  148. +40 −0 lib/util/addDevServerEntrypoints.js
  149. +23 −0 lib/util/createDomain.js
  150. +11,572 −0 package-lock.json
  151. +92 −46 package.json
  152. 0 ssl/.gitkeep
  153. +0 −13 ssl/ca.crt
  154. +0 −10 ssl/ca.csr
  155. +0 −18 ssl/ca.key
  156. +0 −13 ssl/server.crt
  157. +0 −10 ssl/server.csr
  158. +0 −15 ssl/server.key
  159. +5 −0 test/.eslintrc
  160. +29 −0 test/Compress.test.js
  161. +124 −0 test/ContentBase.test.js
  162. +157 −0 test/HistoryApiFallback.test.js
  163. +24 −0 test/Lazy.test.js
  164. +234 −0 test/Proxy.test.js
  165. +93 −0 test/Routes.test.js
  166. +94 −0 test/Util.test.js
  167. +198 −0 test/Validation.test.js
  168. +49 −0 test/cli.test.js
  169. +3 −0 test/fixtures/cli/foo.js
  170. +20 −0 test/fixtures/cli/webpack.config.js
  171. +5 −0 test/fixtures/contentbase-config/foo.js
  172. +1 −0 test/fixtures/contentbase-config/other/foo.html
  173. +1 −0 test/fixtures/contentbase-config/public/index.html
  174. +1 −0 test/fixtures/contentbase-config/public/other.html
  175. +10 −0 test/fixtures/contentbase-config/webpack.config.js
  176. +1 −0 test/fixtures/directory-index.txt
  177. +1 −0 test/fixtures/historyapifallback-2-config/bar.html
  178. +3 −0 test/fixtures/historyapifallback-2-config/foo.js
  179. +1 −0 test/fixtures/historyapifallback-2-config/other.html
  180. +1 −0 test/fixtures/historyapifallback-2-config/random-file
  181. +10 −0 test/fixtures/historyapifallback-2-config/webpack.config.js
  182. +1 −0 test/fixtures/historyapifallback-3-config/bar.html
  183. +5 −0 test/fixtures/historyapifallback-3-config/foo.js
  184. +1 −0 test/fixtures/historyapifallback-3-config/index.html
  185. +19 −0 test/fixtures/historyapifallback-3-config/webpack.config.js
  186. +1 −0 test/fixtures/historyapifallback-config/bar.html
  187. +6 −0 test/fixtures/historyapifallback-config/foo.js
  188. +1 −0 test/fixtures/historyapifallback-config/index.html
  189. +19 −0 test/fixtures/historyapifallback-config/webpack.config.js
  190. +1 −0 test/fixtures/magic-html.txt
  191. +3 −0 test/fixtures/proxy-config/foo.js
  192. +1 −0 test/fixtures/proxy-config/index.html
  193. +10 −0 test/fixtures/proxy-config/webpack.config.js
  194. +3 −0 test/fixtures/simple-config/foo.js
  195. +11 −0 test/fixtures/simple-config/webpack.config.js
  196. +34 −0 test/helper.js
  197. +50 −0 test/helpers/run-webpack-dev-server.js
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["env"]
}
16 changes: 12 additions & 4 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
root = true
# editorconfig.org

[*.js]
indent_style=tab
trim_trailing_whitespace=true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web_modules
43 changes: 17 additions & 26 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
{
"env": {
"node": true
},
"plugins": [
"nodeca"
],
"rules": {
"strict": 0,
"camelcase": 0,
"curly": 0,
"indent": [0, "tab"],
"nodeca/indent": [2, "tabs", 1],
"eol-last": 2,
"no-shadow": 0,
"no-redeclare": 2,
"no-extra-bind": 2,
"no-empty": 0,
"no-process-exit": 2,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-unused-vars": 0,
"consistent-return": 0,
"no-inner-declarations": 2,
"no-loop-func": 2,
"space-before-function-paren": [2, "never"]
}
"extends": "webpack",
"globals": {
"document": true,
"window": true
},
"parserOptions": {
"sourceType": "script"
},
"rules": {
"comma-dangle": ["error", "never"],
"consistent-return": "off",
"no-param-reassign": "off",
"no-underscore-dangle": "off",
"prefer-destructuring": ["error", {"object": false, "array": false}],
"prefer-rest-params": "off",
"strict": ["error", "safe"]
}
}
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
* text=auto
bin/* eol=lf
bin/* eol=lf
53 changes: 53 additions & 0 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!--
Please note that this template is not optional.
Please fill out _ALL_ fields, or your issue may be closed as "invalid."
Please do not delete this template.
Please ask questions on StackOverflow or Gitter (https://gitter.im/webpack/webpack).
General questions, how-to questions, and support requests will be closed.
-->

* Operating System:
* Node Version:
* NPM Version:
* webpack Version:
* webpack-dev-server Version:

<!--
Please place an x, no spaces, in all [ ] that apply
Please note that we are NOT accepting FEATURE requests at this time.
-->

- [ ] This is a **bug**
- [ ] This is a **modification** request

### Code

<!--
If you have a large amount of code to share which demonstrates the problem
you're experiencing, or your webpack config is very large, please provide a link
to your repository rather than pasting code. We'd also encourage you to use a
Github Gist link instead of pasting code. Otherwise, please paste relevant
short snippets below.
For bugs, please do consider providing a link to a stripped-down, bare-bones
repo that can reproduce the problem you're experiencing. Many times, bugs
aren't actual bugs, but rather specific issues with loaders, plugins, or
an environment/OS. Problems with complicated or large applications will almost
always require this to be triaged.
-->

```js
// webpack.config.js
```

```js
// additional code, remove if not needed.
```

### Expected Behavior

### Actual Behavior

### For Bugs; How can we reproduce the behavior?

### For Features; What is the motivation and/or use-case for the feature?
36 changes: 36 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!--
Thank you for submitting a pull request!
Please note that this template is not optional.
Please fill out _ALL_ fields, or your pull request may be rejected.
Please do not delete this template. Please do remove this header to acknowledge this message.`
Please note that we are NOT accepting new FEATURE requests at this time.
Please place an x, no spaces, in all [ ] that apply
-->

- [ ] This is a **bugfix**
- [ ] This is a **code refactor**
- [ ] This is a **test update**
- [ ] This is a **typo fix**
- [ ] This is a **metadata update**

### For Bugs and Features; did you add new tests?

<!-- Please note that we won't approve your changes if you don't add tests. -->

### Motivation / Use-Case

<!--
Please explain the motivation or use-case for making this change.
What existing problem does the pull request solve?
If this Pull Request addresses an issue, please link to the issue.
-->

### Breaking Changes

<!--
If this PR introduces a breaking change, please describe the impact and a
migration path for existing applications.
-->

### Additional Info
8 changes: 6 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
npm-debug.log
node_modules
/client/live.bundle.js
/client/index.bundle.js
/client
/coverage
/ssl/*.pem
.idea/
.DS_Store
25 changes: 0 additions & 25 deletions .jsbeautifyrc

This file was deleted.

21 changes: 18 additions & 3 deletions .travis.yml
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
sudo: false
language: node_js
branches:
only:
- master

language:
node_js

node_js:
- node
script: npm run travis
- '10'
- '8'
- '6'
- '4'

script:
npm run ci

after_success:
- cat ./coverage/coverage.json | node_modules/codecov.io/bin/codecov.io.js
- rm -rf ./coverage
57 changes: 57 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Contributing to webpack-dev-server

Do you use webpack-dev-server and want to help us out? Thanks!

Please review this document before contributing.

Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should show respect in addressing your issue or assessing patches and features.

## Core Ideas

- There are hooks to add your own features, so we should not add less-common features.
- The workflow should be to start webpack-dev-server as a separate process, next to the "normal" server and to request the script from this server or to proxy from dev-server to "normal" server (because webpack blocks the event queue too much while compiling which can affect "normal" server).
- A user should not try to implement stuff that accesses the webpack filesystem. This lead to bugs (the middleware does it while blocking requests until the compilation has finished, the blocking is important).
- It should be a development only tool. Compiling in production is bad, one should precompile and deliver the compiled assets.
- Processing options and stats display is delegated to webpack, so webpack-dev-server/middleware should not do much with it. This also helps us to keep up-to-date with webpack updates.
- The communication library (`SockJS`) should not be exposed to the user.

## Submitting a Pull Request

Good pull requests, such as patches, improvements, and new features, are a fantastic help. They should remain focused in scope and not contain unrelated commits.

It is advised to first create an issue (if there is not one already) before making a pull request. This way the maintainers can first discuss with you if they agree and it also helps with providing some context.

Run the relevant [examples](https://github.com/webpack/webpack-dev-server/tree/master/examples) to see if all functionality still works. When introducing new functionality, also add an example. This helps the maintainers to understand it and check if it still works.

## Setting Up a Local Copy

1. Clone the repo with `git clone https://github.com/webpack/webpack-dev-server`.

2. Run `npm install` in the root `webpack-dev-server` folder.

Once it is done, you can modify any file locally. In the `examples/` directory you'll find a lot of examples with instructions on how to run it. This can be very handy when testing if your code works.

If you are modifying a file in the `client/` directory, be sure to run `npm run prepublish` after it. This will recompile the files.

## Testing a Pull Request

Pull requests often need some real-world testing.

1. In your `package.json`, change the line with `webpack-dev-server` to:

```json
"webpack-dev-server": "webpack/webpack-dev-server#<ID>/head"
```

`<ID>` is the ID of the pull request.

2. Run `npm install`.

3. Go to the `webpack-dev-server` module (`cd node_modules/webpack-dev-server`), and run `npm run prepublish`.

The pull request is now ready to be tested.


------------

*Many thanks to [create-react-app](https://github.com/facebookincubator/create-react-app/blob/master/CONTRIBUTING.md) for the inspiration with this contributing guide*
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
173 changes: 164 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,178 @@
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
</div>

[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]

# webpack-dev-server

**THIS SERVER SHOULD BE USED FOR DEVELOPMENT ONLY!**
Use [webpack](https://webpack.js.org) with a development server that provides
live reloading. This should be used for **development only**.

**DO NOT USE IT IN PRODUCTION!**
It uses [webpack-dev-middleware][middleware-url] under the hood, which provides
fast in-memory access to the webpack assets.

It's a live reloading server for [webpack](http://webpack.github.io).
## Project in Maintenance

# [Documentation](http://webpack.github.io/docs/webpack-dev-server.html)
**Please note that `webpack-dev-server` is presently in a maintenance-only mode**
and will not be accepting any additional features in the near term. Most new feature
requests can be accomplished with Express middleware; please look into using
the [`before`](https://webpack.js.org/configuration/dev-server/#devserver-before)
and [`after`](https://webpack.js.org/configuration/dev-server/#devserver-after)
hooks in the documentation.

## Inspiration
## Getting Started

This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5).
First thing's first, install the module:

```console
npm install webpack-dev-server --save-dev
```

_Note: While you can install and run webpack-dev-server globally, we recommend
installing it locally. webpack-dev-server will always use a local installation
over a global one._

## Usage

There are two main, recommended methods of using the module:

### With the CLI

The easiest way to use it is with the CLI. In the directory where your
`webpack.config.js` is, run:

```console
node_modules/.bin/webpack-dev-server
```

### With NPM Scripts

NPM package.json scripts are a convenient and useful means to run locally installed
binaries without having to be concerned about their full paths. Simply define a
script as such:

```json
"scripts": {
"start:dev": "webpack-dev-server"
}
```

And run the following in your terminal/console:

```console
npm run start:dev
```

NPM will automagically reference the binary in `node_modules` for you, and
execute the file or command.

### The Result

Either method will start a server instance and begin listening for connections
from `localhost` on port `8080`.

webpack-dev-server is configured by default to support live-reload of files as
you edit your assets while the server is running.

See [**the documentation**][docs-url] for more use cases and options.

## Browser Support

While `webpack-dev-server` transpiles the client (browser) scripts to an ES5
state, the project only officially supports the _last two versions of major
browsers_. We simply don't have the resources to support every whacky
browser out there.

If you find an bug with an obscure / old browser, we would actively welcome a
Pull Request to resolve the bug.

## Support

We do our best to keep Issues in the repository focused on bugs, features, and
needed modifications to the code for the module. Because of that, we ask users
with general support, "how-to", or "why isn't this working" questions to try one
of the other support channels that are available.

Your first-stop-shop for support for webpack-dev-server should by the excellent
[documentation][docs-url] for the module. If you see an opportunity for improvement
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
pull request.

From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
talk to the fine folks there. If your quest for answers comes up dry in chat,
head over to [StackOverflow][stack-url] and do a quick search or open a new
question. Remember; It's always much easier to answer questions that include your
`webpack.config.js` and relevant files!

If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
and someone should be able to reach out and lend a hand.

If you have discovered a :bug:, have a feature suggestion, of would like to see
a modification, please feel free to create an issue on Github. _Note: The issue
template isn't optional, so please be sure not to remove it, and please fill it
out completely._

## Contributing

The client scripts are built with `npm run-script prepublish`.
We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved.

## Maintainers

<table>
<tbody>
<tr>
<td align="center">
<img src="https://avatars.githubusercontent.com/SpaceK33z?v=4&s=150">
<br />
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<td align="center">
<img src="https://i.imgur.com/4v6pgxh.png">
<br />
<a href="https://github.com/shellscape">Andrew Powell</a>
</td>
</tr>
</tbody>
</table>

## Attribution

This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5).

## License

Copyright 2012-2014 Tobias Koppers
#### [MIT](./LICENSE)


[npm]: https://img.shields.io/npm/v/webpack-dev-server.svg
[npm-url]: https://npmjs.com/package/webpack-dev-server

[node]: https://img.shields.io/node/v/webpack-dev-server.svg
[node-url]: https://nodejs.org

[deps]: https://david-dm.org/webpack/webpack-dev-server.svg
[deps-url]: https://david-dm.org/webpack/webpack-dev-server

[tests]: http://img.shields.io/travis/webpack/webpack-dev-server.svg
[tests-url]: https://travis-ci.org/webpack/webpack-dev-server

[cover]: https://codecov.io/gh/webpack/webpack-dev-server/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-server

[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack

[MIT](http://www.opensource.org/licenses/mit-license.php)
[docs-url]: https://webpack.js.org/configuration/dev-server/#devserver
[hash-url]: https://twitter.com/search?q=webpack
[middleware-url]: https://github.com/webpack/webpack-dev-middleware
[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-server
[uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
[wjo-url]: https://github.com/webpack/webpack.js.org
588 changes: 442 additions & 146 deletions bin/webpack-dev-server.js

Large diffs are not rendered by default.

243 changes: 243 additions & 0 deletions client-src/default/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
'use strict';

/* global __resourceQuery WorkerGlobalScope self */
/* eslint prefer-destructuring: off */

const url = require('url');
const stripAnsi = require('strip-ansi');
const log = require('loglevel').getLogger('webpack-dev-server');
const socket = require('./socket');
const overlay = require('./overlay');

function getCurrentScriptSource() {
// `document.currentScript` is the most accurate way to find the current script,
// but is not supported in all browsers.
if (document.currentScript) { return document.currentScript.getAttribute('src'); }
// Fall back to getting all scripts in the document.
const scriptElements = document.scripts || [];
const currentScript = scriptElements[scriptElements.length - 1];
if (currentScript) { return currentScript.getAttribute('src'); }
// Fail as there was no script to use.
throw new Error('[WDS] Failed to get current script source.');
}

let urlParts;
let hotReload = true;
if (typeof window !== 'undefined') {
const qs = window.location.search.toLowerCase();
hotReload = qs.indexOf('hotreload=false') === -1;
}
if (typeof __resourceQuery === 'string' && __resourceQuery) {
// If this bundle is inlined, use the resource query to get the correct url.
urlParts = url.parse(__resourceQuery.substr(1));
} else {
// Else, get the url from the <script> this file was called with.
let scriptHost = getCurrentScriptSource();
// eslint-disable-next-line no-useless-escape
scriptHost = scriptHost.replace(/\/[^\/]+$/, '');
urlParts = url.parse((scriptHost || '/'), false, true);
}

if (!urlParts.port || urlParts.port === '0') {
urlParts.port = self.location.port;
}

let hot = false;
let initial = true;
let currentHash = '';
let useWarningOverlay = false;
let useErrorOverlay = false;
let useProgress = false;

const INFO = 'info';
const WARNING = 'warning';
const ERROR = 'error';
const NONE = 'none';

// Set the default log level
log.setDefaultLevel(INFO);

// Send messages to the outside, so plugins can consume it.
function sendMsg(type, data) {
if (
typeof self !== 'undefined' &&
(typeof WorkerGlobalScope === 'undefined' ||
!(self instanceof WorkerGlobalScope))
) {
self.postMessage({
type: `webpack${type}`,
data
}, '*');
}
}

const onSocketMsg = {
hot() {
hot = true;
log.info('[WDS] Hot Module Replacement enabled.');
},
invalid() {
log.info('[WDS] App updated. Recompiling...');
// fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
if (useWarningOverlay || useErrorOverlay) overlay.clear();
sendMsg('Invalid');
},
hash(hash) {
currentHash = hash;
},
'still-ok': function stillOk() {
log.info('[WDS] Nothing changed.');
if (useWarningOverlay || useErrorOverlay) overlay.clear();
sendMsg('StillOk');
},
'log-level': function logLevel(level) {
const hotCtx = require.context('webpack/hot', false, /^\.\/log$/);
if (hotCtx.keys().indexOf('./log') !== -1) {
hotCtx('./log').setLogLevel(level);
}
switch (level) {
case INFO:
case ERROR:
log.setLevel(level);
break;
case WARNING:
// loglevel's warning name is different from webpack's
log.setLevel('warn');
break;
case NONE:
log.disableAll();
break;
default:
log.error(`[WDS] Unknown clientLogLevel '${level}'`);
}
},
overlay(value) {
if (typeof document !== 'undefined') {
if (typeof (value) === 'boolean') {
useWarningOverlay = false;
useErrorOverlay = value;
} else if (value) {
useWarningOverlay = value.warnings;
useErrorOverlay = value.errors;
}
}
},
progress(progress) {
if (typeof document !== 'undefined') {
useProgress = progress;
}
},
'progress-update': function progressUpdate(data) {
if (useProgress) log.info(`[WDS] ${data.percent}% - ${data.msg}.`);
},
ok() {
sendMsg('Ok');
if (useWarningOverlay || useErrorOverlay) overlay.clear();
if (initial) return initial = false; // eslint-disable-line no-return-assign
reloadApp();
},
'content-changed': function contentChanged() {
log.info('[WDS] Content base changed. Reloading...');
self.location.reload();
},
warnings(warnings) {
log.warn('[WDS] Warnings while compiling.');
const strippedWarnings = warnings.map(warning => stripAnsi(warning));
sendMsg('Warnings', strippedWarnings);
for (let i = 0; i < strippedWarnings.length; i++) { log.warn(strippedWarnings[i]); }
if (useWarningOverlay) overlay.showMessage(warnings);

if (initial) return initial = false; // eslint-disable-line no-return-assign
reloadApp();
},
errors(errors) {
log.error('[WDS] Errors while compiling. Reload prevented.');
const strippedErrors = errors.map(error => stripAnsi(error));
sendMsg('Errors', strippedErrors);
for (let i = 0; i < strippedErrors.length; i++) { log.error(strippedErrors[i]); }
if (useErrorOverlay) overlay.showMessage(errors);
initial = false;
},
error(error) {
log.error(error);
},
close() {
log.error('[WDS] Disconnected!');
sendMsg('Close');
}
};

let hostname = urlParts.hostname;
let protocol = urlParts.protocol;


// check ipv4 and ipv6 `all hostname`
if (hostname === '0.0.0.0' || hostname === '::') {
// why do we need this check?
// hostname n/a for file protocol (example, when using electron, ionic)
// see: https://github.com/webpack/webpack-dev-server/pull/384
// eslint-disable-next-line no-bitwise
if (self.location.hostname && !!~self.location.protocol.indexOf('http')) {
hostname = self.location.hostname;
}
}

// `hostname` can be empty when the script path is relative. In that case, specifying
// a protocol would result in an invalid URL.
// When https is used in the app, secure websockets are always necessary
// because the browser doesn't accept non-secure websockets.
if (hostname && (self.location.protocol === 'https:' || urlParts.hostname === '0.0.0.0')) {
protocol = self.location.protocol;
}

const socketUrl = url.format({
protocol,
auth: urlParts.auth,
hostname,
port: urlParts.port,
pathname: urlParts.path == null || urlParts.path === '/' ? '/sockjs-node' : urlParts.path
});

socket(socketUrl, onSocketMsg);

let isUnloading = false;
self.addEventListener('beforeunload', () => {
isUnloading = true;
});

function reloadApp() {
if (isUnloading || !hotReload) {
return;
}
if (hot) {
log.info('[WDS] App hot update...');
// eslint-disable-next-line global-require
const hotEmitter = require('webpack/hot/emitter');
hotEmitter.emit('webpackHotUpdate', currentHash);
if (typeof self !== 'undefined' && self.window) {
// broadcast update to window
self.postMessage(`webpackHotUpdate${currentHash}`, '*');
}
} else {
let rootWindow = self;
// use parent window for reload (in case we're in an iframe with no valid src)
const intervalId = self.setInterval(() => {
if (rootWindow.location.protocol !== 'about:') {
// reload immediately if protocol is valid
applyReload(rootWindow, intervalId);
} else {
rootWindow = rootWindow.parent;
if (rootWindow.parent === rootWindow) {
// if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
applyReload(rootWindow, intervalId);
}
}
});
}

function applyReload(rootWindow, intervalId) {
clearInterval(intervalId);
log.info('[WDS] App updated. Reloading...');
rootWindow.location.reload();
}
}
129 changes: 129 additions & 0 deletions client-src/default/overlay.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
'use strict';

// The error overlay is inspired (and mostly copied) from Create React App (https://github.com/facebookincubator/create-react-app)
// They, in turn, got inspired by webpack-hot-middleware (https://github.com/glenjamin/webpack-hot-middleware).

const ansiHTML = require('ansi-html');
const Entities = require('html-entities').AllHtmlEntities;

const entities = new Entities();

const colors = {
reset: ['transparent', 'transparent'],
black: '181818',
red: 'E36049',
green: 'B3CB74',
yellow: 'FFD080',
blue: '7CAFC2',
magenta: '7FACCA',
cyan: 'C3C2EF',
lightgrey: 'EBE7E3',
darkgrey: '6D7891'
};
ansiHTML.setColors(colors);

function createOverlayIframe(onIframeLoad) {
const iframe = document.createElement('iframe');
iframe.id = 'webpack-dev-server-client-overlay';
iframe.src = 'about:blank';
iframe.style.position = 'fixed';
iframe.style.left = 0;
iframe.style.top = 0;
iframe.style.right = 0;
iframe.style.bottom = 0;
iframe.style.width = '100vw';
iframe.style.height = '100vh';
iframe.style.border = 'none';
iframe.style.zIndex = 9999999999;
iframe.onload = onIframeLoad;
return iframe;
}

function addOverlayDivTo(iframe) {
const div = iframe.contentDocument.createElement('div');
div.id = 'webpack-dev-server-client-overlay-div';
div.style.position = 'fixed';
div.style.boxSizing = 'border-box';
div.style.left = 0;
div.style.top = 0;
div.style.right = 0;
div.style.bottom = 0;
div.style.width = '100vw';
div.style.height = '100vh';
div.style.backgroundColor = 'rgba(0, 0, 0, 0.85)';
div.style.color = '#E8E8E8';
div.style.fontFamily = 'Menlo, Consolas, monospace';
div.style.fontSize = 'large';
div.style.padding = '2rem';
div.style.lineHeight = '1.2';
div.style.whiteSpace = 'pre-wrap';
div.style.overflow = 'auto';
iframe.contentDocument.body.appendChild(div);
return div;
}

let overlayIframe = null;
let overlayDiv = null;
let lastOnOverlayDivReady = null;

function ensureOverlayDivExists(onOverlayDivReady) {
if (overlayDiv) {
// Everything is ready, call the callback right away.
onOverlayDivReady(overlayDiv);
return;
}

// Creating an iframe may be asynchronous so we'll schedule the callback.
// In case of multiple calls, last callback wins.
lastOnOverlayDivReady = onOverlayDivReady;

if (overlayIframe) {
// We're already creating it.
return;
}

// Create iframe and, when it is ready, a div inside it.
overlayIframe = createOverlayIframe(() => {
overlayDiv = addOverlayDivTo(overlayIframe);
// Now we can talk!
lastOnOverlayDivReady(overlayDiv);
});

// Zalgo alert: onIframeLoad() will be called either synchronously
// or asynchronously depending on the browser.
// We delay adding it so `overlayIframe` is set when `onIframeLoad` fires.
document.body.appendChild(overlayIframe);
}

function showMessageOverlay(message) {
ensureOverlayDivExists((div) => {
// Make it look similar to our terminal.
div.innerHTML = `<span style="color: #${
colors.red
}">Failed to compile.</span><br><br>${
ansiHTML(entities.encode(message))}`;
});
}

function destroyErrorOverlay() {
if (!overlayDiv) {
// It is not there in the first place.
return;
}

// Clean up and reset internal state.
document.body.removeChild(overlayIframe);
overlayDiv = null;
overlayIframe = null;
lastOnOverlayDivReady = null;
}

// Successful compilation.
exports.clear = function handleSuccess() {
destroyErrorOverlay();
};

// Compilation with errors (e.g. syntax error or missing modules).
exports.showMessage = function handleMessage(messages) {
showMessageOverlay(messages[0]);
};
42 changes: 42 additions & 0 deletions client-src/default/socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

const SockJS = require('sockjs-client/dist/sockjs');

let retries = 0;
let sock = null;

const socket = function initSocket(url, handlers) {
sock = new SockJS(url);

sock.onopen = function onopen() {
retries = 0;
};

sock.onclose = function onclose() {
if (retries === 0) { handlers.close(); }

// Try to reconnect.
sock = null;

// After 10 retries stop trying, to prevent logspam.
if (retries <= 10) {
// Exponentially increase timeout to reconnect.
// Respectfully copied from the package `got`.
// eslint-disable-next-line no-mixed-operators, no-restricted-properties
const retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
retries += 1;

setTimeout(() => {
socket(url, handlers);
}, retryInMs);
}
};

sock.onmessage = function onmessage(e) {
// This assumes that all data sent via the websocket is JSON.
const msg = JSON.parse(e.data);
if (handlers[msg.type]) { handlers[msg.type](msg.data); }
};
};

module.exports = socket;
22 changes: 22 additions & 0 deletions client-src/default/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules|web_modules/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
plugins: [
new UglifyJSPlugin()
]
};
124 changes: 124 additions & 0 deletions client-src/live/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
'use strict';

/* eslint import/no-extraneous-dependencies: off, global-require: off */

const $ = require('jquery');
const stripAnsi = require('strip-ansi');
const socket = require('../default/socket');
require('./style.css');

let hot = false;
let currentHash = '';

$(() => {
$('body').html(require('./page.pug')());
const status = $('#status');
const okness = $('#okness');
const $errors = $('#errors');
const iframe = $('#iframe');
const header = $('.header');

const contentPage = window.location.pathname.substr('/webpack-dev-server'.length) + window.location.search;

status.text('Connecting to sockjs server...');
$errors.hide();
iframe.hide();
header.css({
borderColor: '#96b5b4'
});

const onSocketMsg = {
hot() {
hot = true;
iframe.attr('src', contentPage + window.location.hash);
},
invalid() {
okness.text('');
status.text('App updated. Recompiling...');
header.css({
borderColor: '#96b5b4'
});
$errors.hide();
if (!hot) iframe.hide();
},
hash(hash) {
currentHash = hash;
},
'still-ok': function stillOk() {
okness.text('');
status.text('App ready.');
header.css({
borderColor: ''
});
$errors.hide();
if (!hot) iframe.show();
},
ok() {
okness.text('');
$errors.hide();
reloadApp();
},
warnings() {
okness.text('Warnings while compiling.');
$errors.hide();
reloadApp();
},
errors: function msgErrors(errors) {
status.text('App updated with errors. No reload!');
okness.text('Errors while compiling.');
$errors.text(`\n${stripAnsi(errors.join('\n\n\n'))}\n\n`);
header.css({
borderColor: '#ebcb8b'
});
$errors.show();
iframe.hide();
},
close() {
status.text('');
okness.text('Disconnected.');
$errors.text('\n\n\n Lost connection to webpack-dev-server.\n Please restart the server to reestablish connection...\n\n\n\n');
header.css({
borderColor: '#ebcb8b'
});
$errors.show();
iframe.hide();
}
};

socket('/sockjs-node', onSocketMsg);

iframe.on('load', () => {
status.text('App ready.');
header.css({
borderColor: ''
});
iframe.show();
});

function reloadApp() {
if (hot) {
status.text('App hot update.');
try {
iframe[0].contentWindow.postMessage(`webpackHotUpdate${currentHash}`, '*');
} catch (e) {
console.warn(e); // eslint-disable-line
}
iframe.show();
} else {
status.text('App updated. Reloading app...');
header.css({
borderColor: '#96b5b4'
});
try {
let old = `${iframe[0].contentWindow.location}`;
if (old.indexOf('about') === 0) old = null;
iframe.attr('src', old || (contentPage + window.location.hash));
if (old) {
iframe[0].contentWindow.location.reload();
}
} catch (e) {
iframe.attr('src', contentPage + window.location.hash);
}
}
}
});
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
41 changes: 41 additions & 0 deletions client-src/live/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules|web_modules/,
use: [
{
loader: 'babel-loader'
}
]
},
{
test: /\.pug$/,
use: [
'pug-loader?self'
]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
plugins: [
new UglifyJSPlugin(),
new CopyPlugin([{
from: path.resolve(__dirname, 'live.html'),
to: path.resolve(__dirname, '../../client/live.html')
}])
]
};
3 changes: 3 additions & 0 deletions client-src/sockjs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';

module.exports = require('sockjs-client');
14 changes: 14 additions & 0 deletions client-src/sockjs/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

// eslint-disable-next-line
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
output: {
library: 'SockJS',
libraryTarget: 'umd'
},
plugins: [
new UglifyJSPlugin()
]
};
96 changes: 0 additions & 96 deletions client/index.js

This file was deleted.

128 changes: 0 additions & 128 deletions client/live.js

This file was deleted.

11 changes: 0 additions & 11 deletions client/webpack.config.js

This file was deleted.

66 changes: 0 additions & 66 deletions example/README.md

This file was deleted.

13 changes: 0 additions & 13 deletions example/alternative.config.js

This file was deleted.

9 changes: 0 additions & 9 deletions example/app.js

This file was deleted.

11 changes: 0 additions & 11 deletions example/inlined.html

This file was deleted.

1 change: 0 additions & 1 deletion example/unparseable.js

This file was deleted.

29 changes: 0 additions & 29 deletions example/webpack.config.array.js

This file was deleted.

10 changes: 0 additions & 10 deletions example/webpack.config.js

This file was deleted.

Binary file added examples/.assets/favicon.ico
Binary file not shown.
Binary file added examples/.assets/geomanist-medium.woff
Binary file not shown.
Binary file added examples/.assets/geomanist-medium.woff2
Binary file not shown.
1 change: 1 addition & 0 deletions examples/.assets/icon-square.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 26 additions & 0 deletions examples/.assets/layout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html>
<head>
<title>WDS ▻ <%= htmlWebpackPlugin.options.title %></title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/.assets/favicon.ico"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400,600|Source+Sans+Pro:400,400i,500,600"/>
<link rel="stylesheet" href="/.assets/style.css"/>
</head>
<body>
<main>
<header>
<h1>
<img src="/.assets/icon-square.svg" style="width: 35px; height: 35px;"/>
webpack-dev-server
</h1>
</header>
<section>
<h2><%= htmlWebpackPlugin.options.title %></h2>
<div id="target"></div>
</section>
</main>
<script src="/bundle.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
104 changes: 104 additions & 0 deletions examples/.assets/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
@font-face {
font-family: 'Geomanist';
font-style: normal;
font-weight: 600;
src: url('assets/geomanist-medium.woff2') format('woff2'),
url('assets/geomanist-medium.woff') format('woff');
}

html,
body {
background-color: #f3f3f3;
color: #2B3A42;
font: 400 10px "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
height: 100%;
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

a {
color: #2086d7;
text-decoration: none;
transition: color 250ms;
}

a:hover {
color: #1a6aab;
}

main {
width: 100%;
max-width: 94.2rem;
margin: 0px auto;
padding: 8rem 2.4rem;
}

h1 {
font-size: 3.4rem;
font-weight: 600;
line-height: 3.4rem;
margin-top: 0;
padding-top: 0;
}

h1 img {
height: 3.4rem;
width: 3.4rem;
vertical-align: middle;
}

h2 {
font-size: 2.8rem;
}

section {
padding: 0 0 0 4.2rem;
}

div, p, table {
font-size: 1.6rem;
}

code {
background-color: rgba(70, 94, 105, 0.06);
border-radius: 3px;
font-family: "Source Code Pro", Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 1.44rem;
margin: 0;
max-width: 100%;
line-height: initial;
overflow: auto;
padding: 2px 6px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
vertical-align: middle;
white-space: normal;
}

#target {
background: #DCF2FD;
border: 0.1rem solid #618ca0;
border-radius: 0.3rem;
color: #618ca0;
margin: 2rem 0;
padding: 2rem;
}

#target.warn {
background: #fcf8e3;
border: 0.1rem solid #8a6d3b;
color: #8a6d3b;
}

#target.pass {
background: #f2f9f4;
border: 0.1rem solid #4db277;
color: #4db277;
}

#target.fail {
background: #f2dede;
border: 0.1rem solid #a94442;
color: #a94442;
}
5 changes: 5 additions & 0 deletions examples/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"no-console": "off"
}
}
29 changes: 29 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Examples

Each example showcases a particular feature of `webpack-dev-server`. You can use
these examples to learn how to use certain features, or as a means to test features
when working on a Pull Request.

An example should be as minimal as possible and consists of at least:

- An `app.js` file - the entry point for an example app.
- A `README.md` file containing information about, and how to run the example app.
- A description of what should happen when running the example.
- A `webpack.config.js` file containing the `webpack` configuration for the example app.

## API versus CLI

API examples can be found in the `api` directory. These examples demonstrate how
to access and run `webpack-dev-server` directly in your application / script.

CLI examples can be found in the `cli` directory. These examples demonstrate how
to run `webpack-dev-server` from the command line in your console / terminal.

## Notes

- Each example's `webpack` config is wrapped with `util.setup`; a helper function
that adds plugins and configuration needed by each example to render in a consistent
and visually pleasing way.
- Examples' `bundle.js` and `index.html` files are compiled and served from memory.
You won't actually see these files written to disk, but if you examine the `webpack`
output, you should see their file indicators.
20 changes: 20 additions & 0 deletions examples/api/middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# API: Custom Middleware

While it's recommended to run `webpack-dev-server` via the CLI, you may also
choose to start a server via the API. This example demonstrates using one of the
few custom middleware options; `before`.

```console
node server.js
```

## What Should Happen

1. Open `http://localhost:8080/` in your preferred browser.
2. You should see the text on the page itself change to read `Success!`.
3. In the console/terminal, you should see the following for each refresh in
the browser:
```
Using middleware for /
Using middleware for /bundle.js
```
6 changes: 6 additions & 0 deletions examples/api/middleware/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
23 changes: 23 additions & 0 deletions examples/api/middleware/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

const Webpack = require('webpack');
const WebpackDevServer = require('../../../lib/Server');
const webpackConfig = require('./webpack.config');

const compiler = Webpack(webpackConfig);
const devServerOptions = Object.assign({}, webpackConfig.devServer, {
stats: {
colors: true
},
before(app) {
app.use((req, res, next) => {
console.log(`Using middleware for ${req.url}`);
next();
});
}
});
const server = new WebpackDevServer(compiler, devServerOptions);

server.listen(8080, '127.0.0.1', () => {
console.log('Starting server on http://localhost:8080');
});
13 changes: 13 additions & 0 deletions examples/api/middleware/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: ['./app.js', '../../client/index.js?http://localhost:8080/'],
output: {
filename: 'bundle.js'
}
});
17 changes: 17 additions & 0 deletions examples/api/simple/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# API: Simple Server

While it's recommended to run `webpack-dev-server` via the CLI, you may also
choose to start a server via the API. This example starts a simple server setup.

```console
node server.js
```

## What should happen

1. Open `http://localhost:8080/` in your preferred browser.
2. You should see the text on the page itself change to read `Success!`.
3. In `app.js`, uncomment the code that results in an error and save. This error
should be visible in the console/terminal and in browser devtools.
4. In `app.js`, uncomment the code that results in a warning. This warning should
be visible in the console/terminal and in browser devtools.
17 changes: 17 additions & 0 deletions examples/api/simple/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

// This results in a warning:
if (!window) {
// eslint-disable-next-line
require(`./${window}parseable.js`);
}

// This results in an error:
// if(!window) {
// require("test");
// }
17 changes: 17 additions & 0 deletions examples/api/simple/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

const Webpack = require('webpack');
const WebpackDevServer = require('../../../lib/Server');
const webpackConfig = require('./webpack.config');

const compiler = Webpack(webpackConfig);
const devServerOptions = Object.assign({}, webpackConfig.devServer, {
stats: {
colors: true
}
});
const server = new WebpackDevServer(compiler, devServerOptions);

server.listen(8080, '127.0.0.1', () => {
console.log('Starting server on http://localhost:8080');
});
13 changes: 13 additions & 0 deletions examples/api/simple/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: ['./app.js', '../../../client/index.js?http://localhost:8080/'],
output: {
filename: 'bundle.js'
}
});
15 changes: 15 additions & 0 deletions examples/cli/bonjour/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Bonjour (ZeroConf)

The Bonjour capability broadcasts server information via ZeroConf when the Server
is started.

To run this example, run this command in your console or terminal:

```console
npm run webpack-dev-server -- --bonjour
```

## What Should Happen

A Zeroconf broadcast should occur, containing data with a type of `http` and a
subtype of `webpack`.
5 changes: 5 additions & 0 deletions examples/cli/bonjour/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const target = document.querySelector('#target');

target.innerHTML = 'Please check your Zeroconf service.';
10 changes: 10 additions & 0 deletions examples/cli/bonjour/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
25 changes: 25 additions & 0 deletions examples/cli/compression/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Gzip Compression

Website gzip compression makes it possible to reduce the file size of a file
to roughly 30% of its original size before the files are sent to the browser.

To run this example, run this command in your console or terminal:

```console
npm run webpack-dev-server -- --open --compress
```

## What should happen

1. The script should open `https://localhost:8080/`.
2. Files being sent to the browser from the `webpack` bundle should be gzipped.
3. Open the console in your browser's devtools and select the _Network_ tab.
4. Find `bundle.js`. The response headers should contain `Content-Encoding: gzip`.

## Notes

Some browsers, such as Chrome, won't show the `Content-Encoding: gzip` within
the _Response Headers_. This has been documented [here](https://github.com/expressjs/compression/issues/96).

To enable `Content-Encoding` for _Response Headers_ in Chrome, you can follow
[this tutorial](https://www.youtube.com/watch?v=47R6uv0RKCk).
6 changes: 6 additions & 0 deletions examples/cli/compression/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
10 changes: 10 additions & 0 deletions examples/cli/compression/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
25 changes: 25 additions & 0 deletions examples/cli/default/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# CLI: Default State

This example demonstrates how to use `webpack-dev-server` in its default, inline
state.

```console
npm run webpack-dev-server -- --open
```

To run your app using an alternative config, use:

```console
npm run webpack-dev-server -- --open --config alternative.config.js
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In `app.js` uncomment the code that results in an error and save.
4. This error should be visible in the console/terminal and in the browser's devtools.
5. In `app.js` uncomment the code that results in a warning. This warning should
be visible in the console/terminal and in the browser's devtools.
6. Try changing something in `style.less`. The browser should refresh, and the
change should be visible in the app.
20 changes: 20 additions & 0 deletions examples/cli/default/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

require('./style.less');

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

const img = document.createElement('img');
img.src = '/svg.svg';
img.style = 'width: 200px;';

document.body.appendChild(img);

// This results in a warning:
// if(!window) require("./" + window + "parseable.js");

// This results in an error:
// if(!window) require("test");
File renamed without changes
2 changes: 1 addition & 1 deletion example/style.less → examples/cli/default/style.less
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
body {
background: url(pixels.png);
}
}
2 changes: 1 addition & 1 deletion example/svg.svg → examples/cli/default/svg.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions examples/cli/default/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
module: {
rules: [
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.png$/,
loader: 'file-loader',
options: { prefix: 'img/' }
}
]
}
});
20 changes: 20 additions & 0 deletions examples/cli/history-api-fallback/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# CLI: History API Fallback Option

This option enables [History API Fallback](https://github.com/bripkens/connect-history-api-fallback)
support in `webpack-dev-server`, effectively asking the server to fallback to
`index.html` in the event that a requested resource cannot be found.

```shell
npm run webpack-dev-server -- --open --history-api-fallback
```

_Note: some URLs don't work by default. For example; if the url contains a dot.
Be sure to checkout the [connect-history-api-fallback](https://github.com/bripkens/connect-history-api-fallback)
options._

## What Should Happen

1. The script should open `http://0.0.0.0:8080/` in your default browser.
2. You should see text on the page that reads 'Current Path: /'.
3. Navigate to `http://localhost:8080/foo/bar`.
4. You should see text on the page that reads 'Current Path: /foo/background'.
75 changes: 75 additions & 0 deletions examples/cli/history-api-fallback/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
'use strict';

/* global XMLHttpRequest */

const path = document.location.pathname;
const target = document.querySelector('#target');
const style = document.createElement('style');
const css = `table {
border-radius: 0.3rem;
border: 0.1rem solid #474747;
border-spacing: 0;
padding: 0;
width: 50%;
}
table td {
border-right: 0.1rem solid #474747;
padding: 0.5rem 1rem;
}
table tr td:last-child {
border-right: 0;
text-align: center;
}
table td.pass {
background: #f2f9f4;
color: #4db277;
}
table td.fail {
background: #f2dede;
color: #a94442;
}`;

style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
target.innerHTML = `Current Path: <code>${path}</code>`;

document.addEventListener('DOMContentLoaded', () => {
if (document.querySelector('#files')) {
return;
}

const tests = [
{ url: '/', name: 'index', re: /^<!doctype html>/i },
{ url: '/test', name: 'non-existent path', re: /^<!doctype html>/i },
{ url: '/file.txt', name: 'existing path', re: /^file/ }
];
const table = document.createElement('table');
const tbody = document.createElement('tbody');

table.id = 'files';
table.appendChild(tbody);
target.parentNode.appendChild(table);

tests.forEach((test) => {
const tr = document.createElement('tr');
tbody.appendChild(tr);
check(test.url, test.re, (res) => {
tr.innerHTML = `<td>${test.name}</td>`;
tr.innerHTML += `<td><a href="${test.url}">${test.url}</a></td>`;
tr.innerHTML += `<td class="${res}">${res}</td>`;
});
});
}, true);

function check(url, re, cb) {
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
cb(re.test(xhr.responseText) ? 'pass' : 'fail');
});
xhr.open('GET', url);
xhr.send();
}
1 change: 1 addition & 0 deletions examples/cli/history-api-fallback/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
file
15 changes: 15 additions & 0 deletions examples/cli/history-api-fallback/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
historyApiFallback: {
disableDotRule: true
}
}
});
30 changes: 30 additions & 0 deletions examples/cli/hmr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Hot Module Reloading

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an
application is running, without a full reload of the page.

To run this example, run this command in your console or terminal:

```console
npm run webpack-dev-server -- --open --hot
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. In your editor, open `example.js` and change any part of the `innerHTML` string.
3. Open the console in your browser's devtools.

In the devtools console you should see:

```
[WDS] App updated. Recompiling...
[WDS] App hot update...
[HMR] Checking for updates on the server...
[HMR] Updated modules:
[HMR] - ./example.js
[HMR] App is up to date.
```

You should also see the text on the page itself change to match your edits in
`example.js`.
11 changes: 11 additions & 0 deletions examples/cli/hmr/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

require('./example');

if (module.hot) {
module.hot.accept((err) => {
if (err) {
console.error('Cannot apply HMR update.', err);
}
});
}
5 changes: 5 additions & 0 deletions examples/cli/hmr/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const target = document.querySelector('#target');

target.innerHTML = 'Modify and save <code>/examples/hmr/example.js</code> to update this element without reloading the page.';
10 changes: 10 additions & 0 deletions examples/cli/hmr/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
24 changes: 24 additions & 0 deletions examples/cli/host-and-port/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# CLI: Host and Port Options

You may choose to wish to change the host and port on which `webpack-dev-server`
will run. The `host` and `port` options allow for that.

## IPv4

```console
npm run webpack-dev-server -- --open --port 5000 --host 0.0.0.0
```

## IPv6

_This also works with IPv4_

```console
npm run webpack-dev-server -- --open --port 5000 --host ::
```

## What Should Happen

1. The script should open `http://0.0.0.0:5000/` if specifying the IPv4 option,
or `http://[::]:5000/` for IPv6, in your default browser.
2. You should see the text on the page itself change to read `Success!`.
6 changes: 6 additions & 0 deletions examples/cli/host-and-port/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
10 changes: 10 additions & 0 deletions examples/cli/host-and-port/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
36 changes: 36 additions & 0 deletions examples/cli/https/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# CLI: Https Option

By default webpack-dev-server will generate a self-signed, 2048 bit, sha256 SSL
Certificate, which is used to enable https. The certificate will be located in the
`ssl` directory after the server is started for the first time. The generated
certificate is only good for 30 days, at which point it'll be regenerated.

We highly recommend creating and managing your own certificates. Please see the
following resources for doing so:

* (MacOS) https://certsimple.com/blog/localhost-ssl-fix
* (Windows) https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

## Getting Started

```shell
npm run webpack-dev-server -- --open --https
```

## Using Your Certificate

Options are available for using your own SSL Certificate in your preferred or
OS-required format.

Given the base command `npm run webpack-dev-server -- --open --https`, append
one of the following:

* (PEM Files) `--cert=../../ssl/server.pem --key=../../ssl/server.pem`
* (PFX and Passphrase) `--pfx=./test_cert.pfx --pfx-passphrase=sample`

## What To Expect

The script should open `https://localhost:8080/`in your default browser. If your
browser displays a warning about a non-trusted certificate, follow the procedure
for your browser of choice to continue. After doing so you should see "It's Working"
displayed on the page.
6 changes: 6 additions & 0 deletions examples/cli/https/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
Binary file added examples/cli/https/test_cert.pfx
Binary file not shown.
10 changes: 10 additions & 0 deletions examples/cli/https/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
19 changes: 19 additions & 0 deletions examples/cli/iframe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# CLI: Inline Iframe

The `--no-inline` option instructs `webpack-dev-server` to open the app in an
iframe. The page then contains the client script to connect to the server.

```shell
npm run webpack-dev-server -- --no-inline --open
```

## What Should Happen

1. The script should open `http://localhost:8080/webpack-dev-server/` in your
default browser.
2. There should be a bar at the top of the page that reads `App ready`.
3. In `app.js`, uncomment the code that results in an error and save.
4. The bar at the top should read `Errors while compiling. App updated with errors.
No reload!` along with a stack trace.
5. In `app.js`, uncomment the code that results in a warning. The bar at the top
should read `Warnings while compiling`.
12 changes: 12 additions & 0 deletions examples/cli/iframe/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

// This results in a warning:
// if(!window) require("./" + window + "parseable.js");

// This results in an error:
// if(!window) require("test");
10 changes: 10 additions & 0 deletions examples/cli/iframe/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
19 changes: 19 additions & 0 deletions examples/cli/lazy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# CLI: Lazy Option

With the `lazy` option enabled, `webpack-dev-server` does **not** watch the
bundle files, nor does it automatically recompile them or refresh the browser.
Instead, it only compiles after you manually refresh the page.

```shell
npm run webpack-dev-server -- --open --lazy --no-inline
```

## What should happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Change something in `app.js` and save.
4. You should not see any changes in the console/terminal output.
5. You should not see any changes in the browser.
6. Refresh the page.
7. You should see compilation in the console/terminal and changes in the browser.
12 changes: 12 additions & 0 deletions examples/cli/lazy/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

// This results in a warning:
// if(!window) require("./" + window + "parseable.js");

// This results in an error:
// if(!window) require("test");
10 changes: 10 additions & 0 deletions examples/cli/lazy/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
50 changes: 50 additions & 0 deletions examples/cli/listen-socket/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# CLI: Socket Option

To run the entire example, start the server with the following command:

```console
npm run webpack-dev-server -- --socket ./webpack.sock
```

And then start node server that will use that socket:

```console
node check-socket.js
```

## What Should Happen

You should see this responses to this command:

```console
Successfully connected to socket, exiting
```

## Use Cases

A common use-case for this feature is configuring upstream in nginx that points
to webpack socket. Listening to socket instead of port is much more convenient
because if you have many applications you don't have to resolve port conflicts
since each of them has own unique socket.

Example of configuring upstream with Websockets support in nginx:

```
location /webpack/ {
proxy_pass http://unix:/home/happywebpackuser/apps/todo/webpack.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://unix:/home/resure/code/statface-raw/app/run/statbox.sock;
proxy_redirect off;
}
location /sockjs-node/ {
proxy_pass http://unix:/home/happywebpackuser/apps/todo/webpack.sock;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
```

Replace `/webpack/` with your `publicPath` param value and path in `proxy_pass`
to your actual proxy location.
6 changes: 6 additions & 0 deletions examples/cli/listen-socket/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
9 changes: 9 additions & 0 deletions examples/cli/listen-socket/check-socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';

const net = require('net');

const client = net.createConnection('./webpack.sock');
client.on('connect', () => {
console.log('Successfully connected to socket, exiting');
process.exit(1); // eslint-disable-line
});
10 changes: 10 additions & 0 deletions examples/cli/listen-socket/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
10 changes: 10 additions & 0 deletions examples/cli/node-false/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# CLI: Webpack `node` Option

```shell
npm run webpack-dev-server -- --open
```

## What should happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
6 changes: 6 additions & 0 deletions examples/cli/node-false/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
11 changes: 11 additions & 0 deletions examples/cli/node-false/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
node: false
});
14 changes: 14 additions & 0 deletions examples/cli/open-page/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# CLI: Open Page Option

```console
npm run webpack-dev-server -- --open-page example.html#page1
```

Some applications may consist of multiple pages. During development it may
be useful to directly open a particular page. The page to open may be specified
as the argument to the `open-page` option.

## What Should Happen

The script should open `http://localhost:8080/` in your default browser.
You should see the text on the page itself change to read `Success!`.
11 changes: 11 additions & 0 deletions examples/cli/open-page/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

const target = document.querySelector('#target');

if (window.location.href.endsWith('example.html#page1')) {
target.classList.add('pass');
target.innerHTML = 'Success!';
} else {
target.classList.add('fail');
target.innerHTML = 'Houston, we have a problem.';
}
18 changes: 18 additions & 0 deletions examples/cli/open-page/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const HtmlWebpackPlugin = require('html-webpack-plugin');
// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
plugins: [
new HtmlWebpackPlugin({
filename: 'example.html',
template: '../../assets/layout.html',
title: 'Open Page / Example'
})
]
});
18 changes: 18 additions & 0 deletions examples/cli/overlay/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# CLI: Overlay Option

`webpack-dev-server` can display an overlay for warnings and errors.

```shell
npm run webpack-dev-server -- --open --overlay
```

_Note: To view additional options for the overlay visit
[https://webpack.js.org/configuration/dev-server/#devserver-overlay](https://webpack.js.org/configuration/dev-server/#devserver-overlay)._

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In `app.js` write code containing a syntax error and save the file.
4. The page should now refresh and show a full screen error overlay, displaying
the syntax error.
9 changes: 9 additions & 0 deletions examples/cli/overlay/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

// This results in an error:
// if(!window) require("test");
10 changes: 10 additions & 0 deletions examples/cli/overlay/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
12 changes: 12 additions & 0 deletions examples/cli/progress/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# CLI: Progress Option

```shell
npm run webpack-dev-server -- --open
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In `app.js` change the text and save.
4. You should see the compilation progress in the browser console.
6 changes: 6 additions & 0 deletions examples/cli/progress/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
13 changes: 13 additions & 0 deletions examples/cli/progress/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
progress: true
}
});
18 changes: 18 additions & 0 deletions examples/cli/public-protocol/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# CLI: Public Option Protocol

```console
npm run webpack-dev-server
```

_NOTE: replace `<insert local ip>` with your local IP Address._

You're now able to explicitly define the protocol used with the `public` option
(have a look to the config provided in `webpack.config.js`).

## What Should Happen

The script should open `http://localhost:8080/` in your default browser.

You should see a failed attempt to establish a connection to `/sockjs-node`
via the explicitly defined `https://localhost:8080`. This fails of course since
we're not hosting https.
5 changes: 5 additions & 0 deletions examples/cli/public-protocol/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const target = document.querySelector('#target');

target.innerHTML = 'Please check the sockjs-info request in devtools, it should try to connect to the protocol + server defined in the public setting.';
8 changes: 8 additions & 0 deletions examples/cli/public-protocol/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<script src="bundle.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
</body>
</html>
15 changes: 15 additions & 0 deletions examples/cli/public-protocol/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
host: '0.0.0.0',
public: 'https://localhost:8080',
disableHostCheck: true
}
});
21 changes: 21 additions & 0 deletions examples/cli/public/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# CLI: Public Option

```console
npm run webpack-dev-server -- --open --host 0.0.0.0 --public <insert local ip>:8080
```

_NOTE: replace `<insert local ip>` with your local IP Address._

In order to make the server publicly accessible the client needs to know with
what host to connect to the server. If `--host 0.0.0.0` is given, the client
would try to connect to `0.0.0.0`. With the `--public` options it is possible to
override this.

## What Should Happen

1. The script should open `http://0.0.0.0:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Open the console in your browser's devtools.
4. Select the 'Network' tab.
5. Select the 'WS' or 'WebSockets' sub-tab.
6. Verify that the WebSocket is connecting to `<insert local ip>:8080`.
6 changes: 6 additions & 0 deletions examples/cli/public/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
10 changes: 10 additions & 0 deletions examples/cli/public/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js'
});
16 changes: 16 additions & 0 deletions examples/cli/stdin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# CLI: Stdin Option

Specifying this option instructs the server to close when `stdin` ends.

```console
npm run webpack-dev-server -- --stdin
```

## What Should Happen

1. The server should begin running.
2. Press `CTL+D` on your keyboard.
3. The server should close.

_Note: the keyboard shortcut for terminating `stdin` can vary depending on the
operating systems._
5 changes: 5 additions & 0 deletions examples/cli/stdin/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const target = document.querySelector('#target');

target.innerHTML = 'Press <code>CTL+D</code> on your keyboard to close the server.';
6 changes: 6 additions & 0 deletions examples/cli/stdin/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

module.exports = {
context: __dirname,
entry: './app.js'
};
42 changes: 42 additions & 0 deletions examples/cli/watch-content-base/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# CLI: Watch Content Base

## Watching a single directory

```console
npm run webpack-dev-server -- --content-base assets --watch-content-base --open
```

### What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In your editor, edit `assets/index.html` and save your changes.
4. The app should reload in the browser.

## Watching an Array of Directories

```js
// webpack.conf.js
module.exports = {
/* ... */
devServer: {
contentBase: [
"assets",
"css",
]
}
}
```

```console
npm run webpack-dev-server -- --watch-content-base --open
```

### What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In your editor, edit `assets/index.html` and save your changes.
4. The app should reload.
5. In your editor, edit `css/styles.css` and save your changes.
6. The app should reload.
6 changes: 6 additions & 0 deletions examples/cli/watch-content-base/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
11 changes: 11 additions & 0 deletions examples/cli/watch-content-base/assets/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" type="text/css" charset="utf-8">
</head>
<body>
<h1>Watch content base</h1>
<div id="mytext"></div>
<script src="bundle.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
3 changes: 3 additions & 0 deletions examples/cli/watch-content-base/css/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h1 {
color: blue;
}
16 changes: 16 additions & 0 deletions examples/cli/watch-content-base/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
contentBase: [
'assets',
'css'
]
}
});
14 changes: 14 additions & 0 deletions examples/general/config-array/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# General: Webpack Config Array

This example demonstrates using a `webpack` config containing an array of configs.

```console
npm run webpack-dev-server -- --open
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Navigate to `http://localhost:8080/bundle2.js`
4. The browser should display a minified JavaScript bundle.
14 changes: 14 additions & 0 deletions examples/general/config-array/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

require('./style.less');

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';

// This results in a warning:
// if(!window) require("./" + window + "parseable.js");

// This results in an error:
// if(!window) require("test");
Binary file added examples/general/config-array/pixels.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions examples/general/config-array/style.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: url(pixels.png);
}
33 changes: 33 additions & 0 deletions examples/general/config-array/svg.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
57 changes: 57 additions & 0 deletions examples/general/config-array/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';

const webpack = require('webpack');
// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = [
setup({
context: __dirname,
entry: './app.js',
module: {
rules: [
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.png$/,
loader: 'file-loader',
options: { prefix: 'img/' }
}
]
}
}),
setup({
context: __dirname,
entry: './app.js',
output: {
filename: 'bundle2.js'
},
module: {
rules: [
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.png$/,
loader: 'url-loader',
options: { limit: 100000 }
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
})
];
13 changes: 13 additions & 0 deletions examples/general/config-promise/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# General: Promise-Based Webpack Config

This example demonstrates using `webpack-dev-server` with a `webpack` config that
returns a `Promise`.

```console
npm run webpack-dev-server -- --open
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
5 changes: 5 additions & 0 deletions examples/general/config-promise/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

// Change the following line and save to see the compilation status

document.write('It works!');
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Promise Config Example</title>
<script src="/bundle.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<br>
<img src="/svg.svg" style="width: 200px;">
<h1>Example: Promise Config</h1>
</body>
</html>
14 changes: 14 additions & 0 deletions examples/general/config-promise/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = new Promise(((resolve) => {
resolve(setup({
context: __dirname,
entry: './app.js',
devServer: {
}
}));
}));
19 changes: 19 additions & 0 deletions examples/general/proxy-advanced/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# General: Proxy Advanced

This example demonstrates a user case whereby the app proxies all urls that start with `/api` to
`http://jsonplaceholder.typicode.com/`, but removes `/api` from the url. So
`http://localhost:8080/api/users` should perform a request to
`http://jsonplaceholder.typicode.com/users`.

```console
npm run webpack-dev-server -- --open
```

## What should happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Navigate to `http://localhost:8080/api/users`.
4. The page should display several JSON objects.
5. Navigate to `http://localhost:8080/api/nope`.
6. The page should display `Bypassed proxy!``.
6 changes: 6 additions & 0 deletions examples/general/proxy-advanced/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
8 changes: 8 additions & 0 deletions examples/general/proxy-advanced/bypass.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<body>
<h1>Example: proxy advanced</h1>

Bypassed proxy!
</body>
</html>
26 changes: 26 additions & 0 deletions examples/general/proxy-advanced/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
proxy: {
'/api': {
target: 'http://jsonplaceholder.typicode.com/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
},
bypass(req) {
if (req.url === '/api/nope') {
return '/bypass.html';
}
}
}
}
}
});
36 changes: 36 additions & 0 deletions examples/general/proxy-hot-reload/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# General: Proxy Hot Reload

```shell
npm run webpack-dev-server -- --open
```

Enables hot reloading for proxy config. If function is provided instead of
object, dev server calls it on each request to get proxy config and replaces proxy middleware if config was changed.

## What should happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Navigate to `http://localhost:8080/api/users`.
4. The page should display several JSON objects.

While the server is running, open `proxy-config.js` and replace the following:

```js
module.exports = {
target: 'http://jsonplaceholder.typicode.com/',
pathRewrite: {
'^/api': ''
}
};
```

with:

```js
module.exports = {
target: 'http://reqres.in/'
};
```

A request to `http://localhost:8080/api/users` should return a response from `http://reqres.in/`.
6 changes: 6 additions & 0 deletions examples/general/proxy-hot-reload/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
20 changes: 20 additions & 0 deletions examples/general/proxy-hot-reload/proxy-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

/**/
module.exports = {
target: 'http://jsonplaceholder.typicode.com/',
pathRewrite: {
'^/api': ''
}
};
/**/

//
// Replace it with following and save the file:
//

/** /
module.exports = {
target: 'http://reqres.in/'
};
/**/
45 changes: 45 additions & 0 deletions examples/general/proxy-hot-reload/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'use strict';

/* eslint global-require: off */
const fs = require('fs');
// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');
const proxyConfig = require('./proxy-config');

let proxyOptions = {
context: '/api',
target: proxyConfig.target,
pathRewrite: proxyConfig.pathRewrite,
changeOrigin: true
};

fs.watch('./proxy-config.js', () => {
delete require.cache[require.resolve('./proxy-config')];
try {
const newProxyConfig = require('./proxy-config');
if (proxyOptions.target !== newProxyConfig.target) {
console.log('Proxy target changed:', newProxyConfig.target);
proxyOptions = {
context: '/api',
target: newProxyConfig.target,
pathRewrite: newProxyConfig.pathRewrite,
changeOrigin: true
};
}
} catch (e) {
// eslint-disable-line
}
});

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
proxy: [
function proxy() {
return proxyOptions;
}
]
}
});
16 changes: 16 additions & 0 deletions examples/general/proxy-simple/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# General: Simple Proxy

```console
npm run webpack-dev-server -- --open
```

In `webpack.config.js` there is a very simple configuration for a proxy. Note that this only works when proxying to a direct ip address. See the proxy-advanced example if you want to proxy to a domain.

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Navigate to `http://localhost:8080/api/hey`.
4. Since the proxy target does not actually exist, the console/terminal should
display an error that reads
`[HPM] PROXY ERROR: ECONNREFUSED. localhost -> http://127.0.0.1:50545/api/hey`.
6 changes: 6 additions & 0 deletions examples/general/proxy-simple/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

const target = document.querySelector('#target');

target.classList.add('pass');
target.innerHTML = 'Success!';
15 changes: 15 additions & 0 deletions examples/general/proxy-simple/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = setup({
context: __dirname,
entry: './app.js',
devServer: {
proxy: {
'/api': 'http://127.0.0.1:50545'
}
}
});
16 changes: 16 additions & 0 deletions examples/general/webworker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# General: WebWorker

This example demonstrates using a WebWorker within an app run by `webpack-dev-server`.

```console
npm run webpack-dev-server
```

## What should happen

1. The main thread sends a message to the Worker.
2. The worker outputs the message in the console.
3. The worker sends a message back to the main thread.
4. The main thread posts the message in the console.

No error, warning or other log traces should be in the console.
11 changes: 11 additions & 0 deletions examples/general/webworker/web.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

/* eslint-env browser */

const worker = new Worker('worker.bundle.js');
worker.onmessage = function onMessage(e) {
console.log('[MAIN]', e);
};
worker.postMessage({
hello: 111
});
22 changes: 22 additions & 0 deletions examples/general/webworker/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

// our setup function adds behind-the-scenes bits to the config that all of our
// examples need
const { setup } = require('../../util');

module.exports = [
setup({
devtool: 'source-map',
target: 'web',
entry: './web.js'
}),
{
devtool: 'source-map',
target: 'webworker',
entry: './worker.js',
output: {
filename: 'worker.bundle.js',
path: __dirname
}
}
];
10 changes: 10 additions & 0 deletions examples/general/webworker/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

/* eslint-env worker */

self.onmessage = function onMessage(e) {
console.log('[WORKER]', e);
self.postMessage({
hello: 222
});
};
76 changes: 76 additions & 0 deletions examples/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
'use strict';

/* eslint-disable import/no-extraneous-dependencies */

const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const marked = require('marked');
const webpack = require('webpack');

module.exports = {
setup(config) {
const defaults = { plugins: [], devServer: {} };
const result = Object.assign(defaults, config);
const before = function before(app) {
app.get('/.assets/*', (req, res) => {
const filename = path.join(__dirname, '/', req.path);
res.sendFile(filename);
});
};
const renderer = new marked.Renderer();
const heading = renderer.heading;
const markedOptions = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer,
xhtml: false
};
const readme = fs.readFileSync('README.md', 'utf-8');

let exampleTitle = '';

renderer.heading = function headingProxy(text, level, raw) {
if (level === 1 && !exampleTitle) {
exampleTitle = text;
}

return heading.call(this, text, level, raw);
};

marked.setOptions(markedOptions);

marked(readme, { renderer });

result.plugins.push(new webpack.NamedModulesPlugin());
result.plugins.push(new HtmlWebpackPlugin({
filename: 'index.html',
template: path.join(__dirname, '.assets/layout.html'),
title: exampleTitle
}));

if (result.devServer.before) {
const proxy = result.devServer.before;
result.devServer.before = function replace(app) {
before(app);
proxy(app);
};
} else {
result.devServer.before = before;
}

result.output = { path: path.dirname(module.parent.filename) };

return result;
}
};
Loading