Skip to content
This repository was archived by the owner on Nov 7, 2023. It is now read-only.

Commit f54fe25

Browse files
committed
Update for dev-server v4
1 parent b764f1e commit f54fe25

File tree

10 files changed

+136
-88
lines changed

10 files changed

+136
-88
lines changed

README.md

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,32 +31,41 @@ const injectScripts = require("webpack-dev-server-inject-scripts");
3131
...
3232

3333
devServer: {
34-
index: "",
3534
port: 8080,
3635
hot: true,
3736
historyApiFallback: true,
37+
devMiddleware: {
38+
index: "",
39+
},
3840
proxy: {
3941
"/": {
40-
target: "http://localhost:1234", // Your backend application here
41-
changeOrigin: true // play nice with upstream https
42+
target: "http://localhost:65535", // Your backend application here
43+
changeOrigin: true, // play nice with upstream https
4244
}
4345
},
44-
before: function(app, server, compiler) {
45-
app.use(injectScripts(compiler));
46-
}
47-
}
46+
setupMiddlewares: (middlewares, devServer) => {
47+
if (!devServer) {
48+
throw new Error('webpack-dev-server is not defined');
49+
}
4850

49-
```
51+
// Optional options
52+
const options = {
53+
ignoredPaths: [/\/ignored/, /\/wp-admin/]
54+
};
5055

51-
The middleware function can take an options argument for additional configuration
56+
middlewares.unshift({
57+
name: 'webpack-dev-server-inject-scripts',
58+
middleware: injectScripts(devServer, options)
59+
});
60+
61+
return middlewares;
62+
},
63+
}
5264

53-
```js
54-
const options = {
55-
ignoredPaths: [/\/umbraco/, /\/wp-admin/]
56-
};
57-
app.use(injectScripts(compiler, options));
5865
```
5966

67+
## Usage
68+
6069
- run backend application
6170
- run webpack-dev-server
6271

example/package.json

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@
44
"description": "demo the point of this thing",
55
"license": "MIT",
66
"scripts": {
7-
"start": "webpack serve"
7+
"start": "concurrently \"http-server -p 65535 upstream\" \"webpack serve\" -n upstream,webpack"
88
},
9-
"dependencies": {
10-
"css-loader": "^5.1.1",
11-
"style-loader": "^2.0.0",
12-
"webpack": "^5.24.4",
13-
"webpack-cli": "^4.5.0",
14-
"webpack-dev-server": "^3.11.2",
15-
"webpack-dev-server-inject-scripts": "file:.."
9+
"devDependencies": {
10+
"css-loader": "^6.7.1",
11+
"style-loader": "^3.3.1",
12+
"webpack": "^5.73.0",
13+
"webpack-cli": "^4.10.0",
14+
"webpack-dev-server": "^4.9.3",
15+
"webpack-dev-server-inject-scripts": "file:..",
16+
"modify-response-middleware": "^1.1.0",
17+
"@types/webpack": "^5.28.0",
18+
"concurrently": "^7.2.2",
19+
"http-server": "^14.1.1"
1620
}
1721
}

example/upstream/demo.css

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body{
2+
background: blue;
3+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Demo</title>
8+
<link rel="stylesheet" href="/demo.css" />
9+
</head>
10+
<body>
11+
<h1>The upstream site > ignored path</h1>
12+
</body>
13+
</html>

example/upstream/index.html

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Demo</title>
8+
<link rel="stylesheet" href="/demo.css" />
9+
</head>
10+
<body>
11+
<h1>The upstream site</h1>
12+
</body>
13+
</html>

example/webpack.config.js

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
const path = require("path");
1+
// @ts-check
22
const injectScripts = require("webpack-dev-server-inject-scripts");
33

4+
/** @type {import('webpack').Configuration} */
45
module.exports = {
56
mode: 'development',
67
entry: {
@@ -16,17 +17,28 @@ module.exports = {
1617
],
1718
},
1819
devServer: {
19-
index: "",
2020
port: 8080,
2121
hot: true,
22+
devMiddleware: {
23+
index: "",
24+
},
2225
proxy: {
2326
"/": {
24-
target: "https://www.ft.com/", // Your backend application here
25-
changeOrigin: true // play nice with upstream https
27+
target: "http://localhost:65535", // Your backend application here
28+
changeOrigin: true, // play nice with upstream https
29+
}
30+
},
31+
setupMiddlewares: (middlewares, devServer) => {
32+
if (!devServer) {
33+
throw new Error('webpack-dev-server is not defined');
2634
}
35+
36+
middlewares.unshift({
37+
name: 'webpack-dev-server-inject-scripts',
38+
middleware: injectScripts(devServer, {ignoredPaths: [/\/ignored/]})
39+
});
40+
41+
return middlewares;
2742
},
28-
before: function (app, server, compiler) {
29-
app.use(injectScripts(compiler));
30-
}
3143
}
3244
};

package-lock.json

Lines changed: 22 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "webpack-dev-server-inject-scripts",
3-
"version": "0.2.2",
3+
"version": "0.3.0",
44
"description": "Injects scripts into html body for proxied requests",
55
"main": "src/index.js",
66
"author": "Paul Johnson (https://github.com/p-m-j)",
@@ -21,7 +21,7 @@
2121
"url": "https://github.com/p-m-j/webpack-dev-server-inject-scripts.git"
2222
},
2323
"dependencies": {
24-
"tamper": "^1.1.0"
24+
"modify-response-middleware": "^1.1.0"
2525
},
2626
"devDependencies": {
2727
"chai": "^4.2.0",

src/WebpackDevServerInjectScriptsPlugin.js

Lines changed: 14 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,24 @@
1-
const pluginName = 'WebpackDevServerInjectScriptsPlugin';
2-
31
const defaultOptions = {
42
ignoredPaths: []
53
};
64

7-
// TODO: Add winston and some logging to aid debugging.
8-
95
class WebpackDevServerInjectScriptsPlugin {
10-
constructor(compiler, options) {
11-
this.files = {};
6+
constructor(devServer, options) {
127
this.options = Object.assign({}, defaultOptions, options);
13-
this.publicPath = compiler.options.output.publicPath.endsWith('/')
14-
? compiler.options.output.publicPath
15-
: compiler.options.output.publicPath + '/';
16-
17-
if (this.publicPath.startsWith('auto/')) {
18-
console.warn(`(${pluginName}) - auto public path may not be handled correctly`)
19-
// TODO: HtmlWebpackPlugin handle this, work it out
20-
this.publicPath = this.publicPath.replace('auto/', '/');
21-
}
22-
23-
compiler.hooks.emit.tap(pluginName, this.onWebpackEmit.bind(this));
24-
}
258

26-
onWebpackEmit(compilation) {
27-
// TODO: HtmlWebpackPlugin file list better
28-
// run compiler.options.entry through some function to establish output filenames.
9+
const entryNames = Object.keys(devServer.compiler.options.entry);
10+
const output = devServer.compiler.options.output;
11+
const filename = devServer.compiler.options.output.filename;
12+
const publicPath = output.publicPath == 'auto' ? '/' : output.publicPath;
2913

30-
const excludeHot = /\.hot-update\.js$/;
31-
const onlyJs = /\.js$/;
32-
compilation.chunks.forEach(chunk => {
33-
chunk.files.forEach(filename => {
34-
if (excludeHot.test(filename)) return;
35-
if (!onlyJs.test(filename)) return;
36-
this.files[`${this.publicPath}${filename}`] = 1;
37-
});
38-
});
14+
this.scripts = entryNames
15+
.map(x => `${publicPath}${filename.replace(/\[name\]/g, x)}`)
16+
.filter(x => x.endsWith('.js'))
17+
.map(x => `<script src="${x}"></script>`)
18+
.join('')
3919
}
4020

4121
shouldTransform(request, response) {
42-
if (response.statusCode != 200) {
43-
return false;
44-
}
45-
4622
if (!/text\/html/.test(response.get('Content-Type'))) {
4723
return false;
4824
}
@@ -51,18 +27,16 @@ class WebpackDevServerInjectScriptsPlugin {
5127
const url = request.originalUrl;
5228
for (const i in this.options.ignoredPaths) {
5329
const ignored = this.options.ignoredPaths[i];
54-
if (url.match(ignored)) return false;
30+
if (url.match(ignored)) {
31+
return false;
32+
}
5533
}
5634

5735
return true;
5836
}
5937

6038
transform(body) {
61-
const scripts = Object.keys(this.files)
62-
.map(x => `<script src="${x}"></script>`)
63-
.join('');
64-
65-
return body.replace('</body>', `${scripts}</body>`)
39+
return body.replace('</body>', `${this.scripts}</body>`)
6640
}
6741
}
6842

src/index.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
1-
const tamper = require('tamper');
1+
const modify = require('modify-response-middleware');
22
const InjectScripts = require('./WebpackDevServerInjectScriptsPlugin');
33

4-
// Prevent gzipped responses
5-
function preventCompression(req, res, next) {
6-
req.headers['accept-encoding'] = 'identity';
4+
// HACK: could try do something with proxy.onProxyRes instead
5+
function omitResponseContentLength(req, res, next) {
6+
const _setHeader = res.setHeader;
7+
res.setHeader = (name, value) => {
8+
if(!/content\-length/i.test(name))
9+
_setHeader.call(res, name, value)
10+
}
711
next();
812
}
913

10-
module.exports = (compiler, options) => {
11-
const plugin = new InjectScripts(compiler, options);
14+
module.exports = (devServer, options) => {
15+
const plugin = new InjectScripts(devServer, options);
1216

13-
const injectScriptsMiddleware = tamper((req, res) => {
14-
if (!plugin.shouldTransform(req, res)) {
15-
return false;
17+
const transformMiddleware = modify((content, req, res) => {
18+
if(!plugin.shouldTransform(req, res)){
19+
return content
1620
}
1721

18-
return plugin.transform.bind(plugin)
22+
return plugin.transform(content.toString());
1923
});
2024

21-
return [preventCompression, injectScriptsMiddleware]
25+
return [omitResponseContentLength, transformMiddleware];
2226
};

0 commit comments

Comments
 (0)