Skip to content

Commit c13aa56

Browse files
authored
feat: added the setupMiddlewares option (#4068)
1 parent 0ed7d9e commit c13aa56

17 files changed

+732
-230
lines changed

Diff for: examples/setup-middlewares/README.md

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# setupMiddlewares
2+
3+
Provides the ability to execute a custom function and apply custom middleware(s).
4+
5+
**webpack.config.js**
6+
7+
```js
8+
module.exports = {
9+
// ...
10+
devServer: {
11+
setupMiddlewares: (middlewares, devServer) => {
12+
if (!devServer) {
13+
throw new Error("webpack-dev-server is not defined");
14+
}
15+
16+
devServer.app.get("/setup-middleware/some/path", (_, response) => {
17+
response.send("setup-middlewares option GET");
18+
});
19+
20+
middlewares.push({
21+
name: "hello-world-test-one",
22+
// `path` is optional
23+
path: "/foo/bar",
24+
middleware: (req, res) => {
25+
res.send("Foo Bar!");
26+
},
27+
});
28+
29+
middlewares.push((req, res) => {
30+
res.send("Hello World!");
31+
});
32+
33+
return middlewares;
34+
},
35+
},
36+
};
37+
```
38+
39+
To run this example use the following command:
40+
41+
```console
42+
npx webpack serve --open
43+
```
44+
45+
## What Should Happen
46+
47+
1. The script should open `http://localhost:8080/` in your default browser.
48+
2. You should see the text on the page itself change to read `Success!`.
49+
3. Go to `http://localhost:8080/setup-middleware/some/path`, you should see the text on the page itself change to read `setup-middlewares option GET`.

Diff for: examples/setup-middlewares/app.js

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"use strict";
2+
3+
const target = document.querySelector("#target");
4+
5+
target.classList.add("pass");
6+
target.innerHTML = "Success!";

Diff for: examples/setup-middlewares/webpack.config.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"use strict";
2+
3+
// our setup function adds behind-the-scenes bits to the config that all of our
4+
// examples need
5+
const { setup } = require("../util");
6+
7+
module.exports = setup({
8+
context: __dirname,
9+
entry: "./app.js",
10+
devServer: {
11+
setupMiddlewares: (middlewares, devServer) => {
12+
if (!devServer) {
13+
throw new Error("webpack-dev-server is not defined");
14+
}
15+
16+
devServer.app.get("/setup-middleware/some/path", (_, response) => {
17+
response.send("setup-middlewares option GET");
18+
});
19+
20+
middlewares.push({
21+
name: "hello-world-test-one",
22+
// `path` is optional
23+
path: "/foo/bar",
24+
middleware: (req, res) => {
25+
res.send("Foo Bar!");
26+
},
27+
});
28+
29+
middlewares.push((req, res) => {
30+
res.send("Hello World!");
31+
});
32+
33+
return middlewares;
34+
},
35+
},
36+
});

0 commit comments

Comments
 (0)