Skip to content

Add option historyApiFallback #922

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ The public path that the middleware is bound to.

_Best Practice: use the same `publicPath` defined in your webpack config. For more information about `publicPath`, please see [the webpack documentation](https://webpack.js.org/guides/public-path)._

### historyApiFallback

type: `Boolean`
Default: `false`

When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. Enable historyApiFallback by setting it to true

### stats

Type: `Boolean|String|Object`
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const noop = () => {};
*/

/**
* @typedef {Compiler["outputFileSystem"] & { createReadStream?: import("fs").createReadStream, statSync?: import("fs").statSync, lstat?: import("fs").lstat, readFileSync?: import("fs").readFileSync }} OutputFileSystem
* @typedef {Compiler["outputFileSystem"] & { createReadStream?: import("fs").createReadStream, statSync?: import("fs").statSync, lstat?: import("fs").lstat, existsSync?: import("fs").existsSync, readFileSync?: import("fs").readFileSync }} OutputFileSystem
*/

/** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
Expand Down Expand Up @@ -88,6 +88,7 @@ const noop = () => {};
* @property {boolean} [serverSideRender]
* @property {OutputFileSystem} [outputFileSystem]
* @property {boolean | string} [index]
* @property {boolean | undefined} [historyApiFallback]
*/

/**
Expand Down
4 changes: 4 additions & 0 deletions src/options.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@
}
]
},
"historyApiFallback": {
"description": "When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. Enable historyApiFallback by setting it to true",
"type": "boolean"
},
"stats": {
"description": "Stats options object or preset name.",
"link": "https://github.com/webpack/webpack-dev-middleware#stats",
Expand Down
9 changes: 8 additions & 1 deletion src/utils/getFilenameFromUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,15 @@ function getFilenameFromUrl(context, url) {
filename = path.join(outputPath, querystring.unescape(pathname));
}

let fsStats;
if (
context.outputFileSystem.existsSync &&
!context.outputFileSystem.existsSync(filename) &&
options.historyApiFallback
) {
filename = path.join(outputPath);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need path.join here, it doesn't have sense

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will check. Look like mistake. May be we need change it to path.resolve

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now this code looks like this option is not necessarily at all.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything should work without this option.
I am confused.
I feel that i need cancel this PR.

}

let fsStats;
try {
fsStats =
/** @type {import("fs").statSync} */
Expand Down
21 changes: 21 additions & 0 deletions test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3040,6 +3040,27 @@ describe.each([
});
});

describe("historyApiFallback option", () => {
describe("index.html page will likely have to be served in place of any 404 responses", () => {
beforeAll((done) => {
const compiler = getCompiler(webpackConfig);

instance = middleware(compiler, { historyApiFallback: true });

app = framework();
app.use(instance);

listen = listenShorthand(done);
});

afterAll(close);

it('should return the "200" code for the "GET" request', (done) => {
request(app).get("/foo/bar/baz").expect(200, done);
});
});
});

describe("serverSideRender option", () => {
let locals;

Expand Down
4 changes: 4 additions & 0 deletions test/validation-options.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ describe("validation", () => {
success: ["/foo", "", "auto", () => "/public/path"],
failure: [false],
},
historyApiFallback: {
success: [true],
failure: [],
},
serverSideRender: {
success: [true],
failure: ["foo", 0],
Expand Down
243 changes: 112 additions & 131 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export = wdm;
* @typedef {ReturnType<Compiler["watch"]>} MultiWatching
*/
/**
* @typedef {Compiler["outputFileSystem"] & { createReadStream?: import("fs").createReadStream, statSync?: import("fs").statSync, lstat?: import("fs").lstat, readFileSync?: import("fs").readFileSync }} OutputFileSystem
* @typedef {Compiler["outputFileSystem"] & { createReadStream?: import("fs").createReadStream, statSync?: import("fs").statSync, lstat?: import("fs").lstat, existsSync?: import("fs").existsSync, readFileSync?: import("fs").readFileSync }} OutputFileSystem
*/
/** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
/**
Expand Down Expand Up @@ -66,6 +66,7 @@ export = wdm;
* @property {boolean} [serverSideRender]
* @property {OutputFileSystem} [outputFileSystem]
* @property {boolean | string} [index]
* @property {boolean | undefined} [historyApiFallback]
*/
/**
* @template {IncomingMessage} RequestInternal
Expand Down Expand Up @@ -115,148 +116,128 @@ export = wdm;
* @param {Options<RequestInternal, ResponseInternal>} [options]
* @returns {API<RequestInternal, ResponseInternal>}
*/
declare function wdm<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
>(
compiler: Compiler | MultiCompiler,
options?: Options<RequestInternal, ResponseInternal> | undefined
declare function wdm<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse>(
compiler: Compiler | MultiCompiler,
options?: Options<RequestInternal, ResponseInternal> | undefined
): API<RequestInternal, ResponseInternal>;
declare namespace wdm {
export {
Schema,
Compiler,
MultiCompiler,
Configuration,
Stats,
MultiStats,
ExtendedServerResponse,
IncomingMessage,
ServerResponse,
NextFunction,
WatchOptions,
Watching,
MultiWatching,
OutputFileSystem,
Logger,
Callback,
Context,
Headers,
Options,
Middleware,
GetFilenameFromUrl,
WaitUntilValid,
Invalidate,
Close,
AdditionalMethods,
API,
};
export {
Schema,
Compiler,
MultiCompiler,
Configuration,
Stats,
MultiStats,
ExtendedServerResponse,
IncomingMessage,
ServerResponse,
NextFunction,
WatchOptions,
Watching,
MultiWatching,
OutputFileSystem,
Logger,
Callback,
Context,
Headers,
Options,
Middleware,
GetFilenameFromUrl,
WaitUntilValid,
Invalidate,
Close,
AdditionalMethods,
API,
};
}
type ServerResponse = import("http").ServerResponse & ExtendedServerResponse;
type Compiler = import("webpack").Compiler;
type MultiCompiler = import("webpack").MultiCompiler;
type Options<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> = {
mimeTypes?:
| {
[key: string]: string;
}
| undefined;
writeToDisk?: boolean | ((targetPath: string) => boolean) | undefined;
methods?: string | undefined;
headers?: Headers<RequestInternal, ResponseInternal>;
publicPath?: NonNullable<Configuration["output"]>["publicPath"];
stats?: Configuration["stats"];
serverSideRender?: boolean | undefined;
outputFileSystem?: OutputFileSystem | undefined;
index?: string | boolean | undefined;
type ServerResponse = import('http').ServerResponse & ExtendedServerResponse;
type Compiler = import('webpack').Compiler;
type MultiCompiler = import('webpack').MultiCompiler;
type Options<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> = {
mimeTypes?:
| {
[key: string]: string;
}
| undefined;
writeToDisk?: boolean | ((targetPath: string) => boolean) | undefined;
methods?: string | undefined;
headers?: Headers<RequestInternal, ResponseInternal>;
publicPath?: NonNullable<Configuration['output']>['publicPath'];
stats?: Configuration['stats'];
serverSideRender?: boolean | undefined;
outputFileSystem?: OutputFileSystem | undefined;
index?: string | boolean | undefined;
historyApiFallback?: boolean | undefined;
};
type API<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> = Middleware<RequestInternal, ResponseInternal> &
AdditionalMethods<RequestInternal, ResponseInternal>;
type Schema = import("schema-utils/declarations/validate").Schema;
type Configuration = import("webpack").Configuration;
type Stats = import("webpack").Stats;
type MultiStats = import("webpack").MultiStats;
type API<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> = Middleware<
RequestInternal,
ResponseInternal
> &
AdditionalMethods<RequestInternal, ResponseInternal>;
type Schema = import('schema-utils/declarations/validate').Schema;
type Configuration = import('webpack').Configuration;
type Stats = import('webpack').Stats;
type MultiStats = import('webpack').MultiStats;
type ExtendedServerResponse = {
locals?:
| {
webpack?:
| {
devMiddleware?:
| Context<import("http").IncomingMessage, ServerResponse>
| undefined;
}
| undefined;
}
| undefined;
locals?:
| {
webpack?:
| {
devMiddleware?: Context<import('http').IncomingMessage, ServerResponse> | undefined;
}
| undefined;
}
| undefined;
};
type IncomingMessage = import("http").IncomingMessage;
type IncomingMessage = import('http').IncomingMessage;
type NextFunction = (err?: any) => void;
type WatchOptions = NonNullable<Configuration["watchOptions"]>;
type Watching = Compiler["watching"];
type MultiWatching = ReturnType<Compiler["watch"]>;
type OutputFileSystem = Compiler["outputFileSystem"] & {
createReadStream?: typeof import("fs").createReadStream;
statSync?: import("fs").StatSyncFn;
lstat?: typeof import("fs").lstat;
readFileSync?: typeof import("fs").readFileSync;
type WatchOptions = NonNullable<Configuration['watchOptions']>;
type Watching = Compiler['watching'];
type MultiWatching = ReturnType<Compiler['watch']>;
type OutputFileSystem = Compiler['outputFileSystem'] & {
createReadStream?: typeof import('fs').createReadStream;
statSync?: import('fs').StatSyncFn;
lstat?: typeof import('fs').lstat;
existsSync?: typeof import('fs').existsSync;
readFileSync?: typeof import('fs').readFileSync;
};
type Logger = ReturnType<Compiler["getInfrastructureLogger"]>;
type Callback = (
stats?: import("webpack").Stats | import("webpack").MultiStats | undefined
) => any;
type Context<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> = {
state: boolean;
stats: Stats | MultiStats | undefined;
callbacks: Callback[];
options: Options<RequestInternal, ResponseInternal>;
compiler: Compiler | MultiCompiler;
watching: Watching | MultiWatching;
logger: Logger;
outputFileSystem: OutputFileSystem;
type Logger = ReturnType<Compiler['getInfrastructureLogger']>;
type Callback = (stats?: import('webpack').Stats | import('webpack').MultiStats | undefined) => any;
type Context<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> = {
state: boolean;
stats: Stats | MultiStats | undefined;
callbacks: Callback[];
options: Options<RequestInternal, ResponseInternal>;
compiler: Compiler | MultiCompiler;
watching: Watching | MultiWatching;
logger: Logger;
outputFileSystem: OutputFileSystem;
};
type Headers<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> =
| Record<string, string | number>
| {
key: string;
value: number | string;
}[]
| ((
req: RequestInternal,
res: ResponseInternal,
context: Context<RequestInternal, ResponseInternal>
) => void | undefined | Record<string, string | number>)
| undefined;
type Middleware<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> = (
req: RequestInternal,
res: ResponseInternal,
next: NextFunction
type Headers<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> =
| Record<string, string | number>
| {
key: string;
value: number | string;
}[]
| ((
req: RequestInternal,
res: ResponseInternal,
context: Context<RequestInternal, ResponseInternal>
) => void | undefined | Record<string, string | number>)
| undefined;
type Middleware<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> = (
req: RequestInternal,
res: ResponseInternal,
next: NextFunction
) => Promise<void>;
type GetFilenameFromUrl = (url: string) => string | undefined;
type WaitUntilValid = (callback: Callback) => any;
type Invalidate = (callback: Callback) => any;
type Close = (callback: (err: Error | null | undefined) => void) => any;
type AdditionalMethods<
RequestInternal extends import("http").IncomingMessage,
ResponseInternal extends ServerResponse
> = {
getFilenameFromUrl: GetFilenameFromUrl;
waitUntilValid: WaitUntilValid;
invalidate: Invalidate;
close: Close;
context: Context<RequestInternal, ResponseInternal>;
type AdditionalMethods<RequestInternal extends import('http').IncomingMessage, ResponseInternal extends ServerResponse> = {
getFilenameFromUrl: GetFilenameFromUrl;
waitUntilValid: WaitUntilValid;
invalidate: Invalidate;
close: Close;
context: Context<RequestInternal, ResponseInternal>;
};
17 changes: 7 additions & 10 deletions types/middleware.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ export = wrapper;
* @param {import("./index.js").Context<Request, Response>} context
* @return {import("./index.js").Middleware<Request, Response>}
*/
declare function wrapper<
Request_1 extends import("http").IncomingMessage,
Response_1 extends import("./index.js").ServerResponse
>(
context: import("./index.js").Context<Request_1, Response_1>
): import("./index.js").Middleware<Request_1, Response_1>;
declare function wrapper<Request_1 extends import('http').IncomingMessage, Response_1 extends import('./index.js').ServerResponse>(
context: import('./index.js').Context<Request_1, Response_1>
): import('./index.js').Middleware<Request_1, Response_1>;
declare namespace wrapper {
export { NextFunction, IncomingMessage, ServerResponse };
export { NextFunction, IncomingMessage, ServerResponse };
}
type NextFunction = import("./index.js").NextFunction;
type IncomingMessage = import("./index.js").IncomingMessage;
type ServerResponse = import("./index.js").ServerResponse;
type NextFunction = import('./index.js').NextFunction;
type IncomingMessage = import('./index.js').IncomingMessage;
type ServerResponse = import('./index.js').ServerResponse;
Loading