Add types for react-dev-utils

This commit is contained in:
ark120202 2019-01-28 17:46:34 +05:00
parent 3317a1c2cf
commit 04d8b844c5
No known key found for this signature in database
GPG Key ID: FA883F1E28DBAF16
26 changed files with 406 additions and 0 deletions

View File

@ -0,0 +1,27 @@
import webpack = require('webpack');
export interface OpaqueFileSizes {
root: string;
sizes: Record<string, number>;
}
/**
* Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the
* result value to compare it after the build.
*/
export function measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>;
/**
* Prints the JS and CSS asset sizes after the build, and includes a size
* comparison with `previousFileSizes` that were captured earlier using
* `measureFileSizesBeforeBuild()`. `maxBundleGzipSize` and
* `maxChunkGzipSizemay` may optionally be specified to display a warning when
* the main bundle or a chunk exceeds the specified size (in bytes).
*/
export function printFileSizesAfterBuild(
webpackStats: webpack.Stats,
previousFileSizes: OpaqueFileSizes,
buildFolder: string,
maxBundleGzipSize?: number,
maxChunkGzipSize?: number,
): void;

View File

@ -0,0 +1,11 @@
import webpack = require('webpack');
import HtmlWebpackPlugin = require('html-webpack-plugin');
/**
* This Webpack plugin inlines script chunks into `index.html`.
*/
declare class InlineChunkHtmlPlugin extends webpack.Plugin {
constructor(htmlWebpackPlugin: HtmlWebpackPlugin, tests: ReadonlyArray<RegExp>);
}
export = InlineChunkHtmlPlugin;

View File

@ -0,0 +1,11 @@
import webpack = require('webpack');
import HtmlWebpackPlugin = require('html-webpack-plugin');
/**
* This Webpack plugin lets us interpolate custom variables into `index.html`.
*/
declare class InterpolateHtmlPlugin extends webpack.Plugin {
constructor(htmlWebpackPlugin: HtmlWebpackPlugin, replacements: { [key: string]: string });
}
export = InterpolateHtmlPlugin;

View File

@ -0,0 +1,11 @@
import webpack = require('webpack');
/**
* This Webpack plugin ensures that relative imports from app's source
* directories don't reach outside of it.
*/
declare class ModuleScopePlugin extends webpack.Plugin {
constructor(appSrc: string | ReadonlyArray<string>, allowedFiles?: ReadonlyArray<string>);
}
export = ModuleScopePlugin;

View File

@ -0,0 +1,10 @@
import webpack = require('webpack');
/**
* This Webpack plugin ensures `npm install <library>` forces a project rebuild.
*/
declare class WatchMissingNodeModulesPlugin extends webpack.Plugin {
constructor(nodeModulesPath: string);
}
export = WatchMissingNodeModulesPlugin;

View File

@ -0,0 +1,46 @@
import webpack = require('webpack');
import WebpackDevServer = require('webpack-dev-server');
export interface Urls {
lanUrlForConfig?: string;
lanUrlForTerminal?: string;
localUrlForTerminal: string;
localUrlForBrowser: string;
}
/**
* Returns a Promise resolving to either `defaultPort` or next available port
* if the user confirms it is okay to do. If the port is taken and the user has
* refused to use another port, or if the terminal is not interactive and cant
* present user with the choice, resolves to `null`.
*/
export function choosePort(host: string, defaultPort: number): Promise<number | null>;
/**
* Creates a Webpack compiler instance for WebpackDevServer with built-in
* helpful messages. Takes the `require('webpack')` entry point as the first
* argument. To provide the `urls` argument, use `prepareUrls()` described
* below.
*/
export function createCompiler(
_webpack: typeof webpack,
config: webpack.Configuration,
appName: string,
urls: Urls,
useYarn: boolean,
): webpack.Compiler;
/**
* Creates a WebpackDevServer `proxy` configuration object from the `proxy`
* setting in `package.json`.
*/
export function prepareProxy(
proxySetting: any,
appPublicFolder: string,
): WebpackDevServer.Configuration;
/**
* Returns an object with local and remote URLs for the development server.
* Pass this object to `createCompiler()` described above.
*/
export function prepareUrls(protocol: string, host: string, port: number): Urls;

View File

@ -0,0 +1,9 @@
/**
* Makes sure that all passed files exist.
*
* Filenames are expected to be absolute.
*
* If a file is not found, prints a warning message and returns `false`.
*/
declare function checkRequiredFiles(files: ReadonlyArray<string>): boolean;
export = checkRequiredFiles;

View File

@ -0,0 +1,5 @@
/**
* Clears the console, hopefully in a cross-platform way.
*/
declare function clearConsole(): void;
export = clearConsole;

View File

@ -0,0 +1,9 @@
import { CLIEngine } from 'eslint';
/**
* This is our custom ESLint formatter that integrates well with
* Create React App console output.
*/
declare function eslintFormatter(results: ReadonlyArray<CLIEngine.LintResult>): string;
export = eslintFormatter;

View File

@ -0,0 +1,16 @@
declare namespace formatWebpackMessages {
interface WebpackMessages {
errors: string[];
warnings: string[];
}
}
/**
* Extracts and prettifies warning and error messages from webpack
* [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object.
*/
declare function formatWebpackMessages(
json: formatWebpackMessages.WebpackMessages,
): formatWebpackMessages.WebpackMessages;
export = formatWebpackMessages;

View File

@ -0,0 +1,18 @@
import webpack = require('webpack');
/**
* Creates a class name for CSS Modules that uses either the filename or folder
* name if named `index.module.css`.
*
* For `MyFolder/MyComponent.module.css` and class `MyClass` the output will be
* `MyComponent.module_MyClass__[hash]`. For `MyFolder/index.module.css` and
* class `MyClass` the output will be `MyFolder_MyClass__[hash]`
*/
declare function getCSSModuleLocalIdent(
context: webpack.loader.LoaderContext,
localIdentName: string,
localName: string,
options: object,
): string;
export = getCSSModuleLocalIdent;

View File

@ -0,0 +1,6 @@
/**
* Returns a cache identifier (string) consisting of the specified environment
* and related package versions.
*/
declare function getCacheIdentifier(environment: string, packages: ReadonlyArray<string>): string;
export = getCacheIdentifier;

View File

@ -0,0 +1,6 @@
/**
* Finds the currently running process on `port`.
* Returns a string containing the name and directory.
*/
declare function getProcessForPort(port: number): string | null;
export = getProcessForPort;

7
types/react-dev-utils/index.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
// Type definitions for react-dev-utils 7.0
// Project: https://github.com/facebook/create-react-app#readme
// Definitions by: ark120202 <https://github.com/ark120202>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export {};

View File

@ -0,0 +1,8 @@
/**
* On macOS, tries to find a known running editor process and opens the file in
* it. It can also be explicitly configured by `REACT_EDITOR`, `VISUAL`, or
* `EDITOR` environment variables. For example, you can put `REACT_EDITOR=atom`
* in your `.env.local` file, and Create React App will respect that.
*/
declare function launchEditor(fileName: string, lineNumber: number, colNumber?: number): void;
export = launchEditor;

View File

@ -0,0 +1,9 @@
import express = require('express');
/**
* Returns Express middleware that serves a `/service-worker.js` that resets
* any previously set service worker configuration. Useful for development.
*/
declare function noopServiceWorkerMiddleware(): express.Handler;
export = noopServiceWorkerMiddleware;

View File

@ -0,0 +1,9 @@
/**
* Attempts to open the browser with a given URL.
*
* On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript.
*
* Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior.
*/
declare function openBrowser(url: string): boolean;
export = openBrowser;

View File

@ -0,0 +1,6 @@
/**
* Prettify some known build errors.
* Pass an Error object to log a prettified error message in the console.
*/
declare function printBuildError(error: Error): void;
export = printBuildError;

View File

@ -0,0 +1,12 @@
/**
* Prints hosting instructions after the project is built.
*/
declare function printHostingInstructions(
appPackage: object,
publicUrl: string,
publicPath: string,
buildFolder: string,
useYarn: boolean,
): void;
export = printHostingInstructions;

View File

@ -0,0 +1,13 @@
import { CLIEngine } from 'eslint';
import eslintFormatter = require('react-dev-utils/eslintFormatter');
const { results } = new CLIEngine({}).executeOnText('');
// $ExpectError
eslintFormatter(['error']);
// $ExpectError
eslintFormatter([results]);
// $ExpectType string
eslintFormatter(results);

View File

@ -0,0 +1,6 @@
import express = require('express');
import noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const app = express();
app.use(noopServiceWorkerMiddleware());
app.listen(8080);

View File

@ -0,0 +1,31 @@
import webpack = require('webpack');
import checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
import clearConsole = require('react-dev-utils/clearConsole');
import getProcessForPort = require('react-dev-utils/getProcessForPort');
import launchEditor = require('react-dev-utils/launchEditor');
import openBrowser = require('react-dev-utils/openBrowser');
import printHostingInstructions = require('react-dev-utils/printHostingInstructions');
import getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
// $ExpectType boolean
checkRequiredFiles(['public/index.html', 'src/index.js']);
// $ExpectType void
clearConsole();
// $ExpectType string | null
getProcessForPort(3000);
// $ExpectType void
launchEditor(__filename, 2);
// $ExpectType void
launchEditor(__filename, 2, 10);
// $ExpectType boolean
openBrowser('http://localhost:3000');
// $ExpectType void
printHostingInstructions({}, '', '', 'build', true);
// $ExpectType string
getCacheIdentifier('prod', ['react-dev-utils', 'chalk']);

View File

@ -0,0 +1,22 @@
import webpack = require('webpack');
import HtmlWebpackPlugin = require('html-webpack-plugin');
import InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
import InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
import ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
import WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
// $ExpectError
new InterpolateHtmlPlugin(HtmlWebpackPlugin, { PUBLIC_URL: 0 });
const plugin1 = new InterpolateHtmlPlugin(HtmlWebpackPlugin, { PUBLIC_URL: '' });
// $ExpectError
new InlineChunkHtmlPlugin({}, [/runtime/]);
const plugin2 = new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime/]);
const plugin3 = new ModuleScopePlugin('src', ['package.json']);
const plugin4 = new WatchMissingNodeModulesPlugin('node_modules');
const configWithPlugins: webpack.Configuration = {
plugins: [plugin1, plugin2, plugin3, plugin4]
};

View File

@ -0,0 +1,52 @@
import webpack = require('webpack');
import FileSizeReporter = require('react-dev-utils/FileSizeReporter');
import formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
import printBuildError = require('react-dev-utils/printBuildError');
import WebpackDevServerUtils = require('react-dev-utils/WebpackDevServerUtils');
import getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
FileSizeReporter.measureFileSizesBeforeBuild('src').then(previousFileSizes => {
webpack().run((err, webpackStats) => {
FileSizeReporter.printFileSizesAfterBuild(webpackStats, previousFileSizes, 'src');
});
});
webpack().run((err, stats) => {
const rawMessages = stats.toJson();
const messages = formatWebpackMessages(rawMessages);
if (!messages.errors.length && !messages.warnings.length) {
console.log('Compiled successfully!');
}
if (messages.errors.length) {
console.log('Failed to compile.');
messages.errors.forEach(e => console.log(e));
return;
}
if (messages.warnings.length) {
console.log('Compiled with warnings.');
messages.warnings.forEach(w => console.log(w));
}
});
webpack().run((err) => {
if (err) printBuildError(err);
});
// $ExpectType Promise<number | null>
WebpackDevServerUtils.choosePort('localhost', 3000);
// $ExpectType Urls
const urls = WebpackDevServerUtils.prepareUrls('http', 'localhost', 3000);
// $ExpectType Compiler
WebpackDevServerUtils.createCompiler(webpack, {}, 'app', urls, true);
// $ExpectType Configuration
WebpackDevServerUtils.prepareProxy(undefined, 'build');
const loaderContext: webpack.loader.LoaderContext = null!;
// $ExpectType string
getCSSModuleLocalIdent(loaderContext, '', '', {});
// $ExpectError
getCSSModuleLocalIdent({}, '', '', {});

View File

@ -0,0 +1,45 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"checkRequiredFiles.d.ts",
"clearConsole.d.ts",
"eslintFormatter.d.ts",
"FileSizeReporter.d.ts",
"formatWebpackMessages.d.ts",
"getCacheIdentifier.d.ts",
"getCSSModuleLocalIdent.d.ts",
"getProcessForPort.d.ts",
"InlineChunkHtmlPlugin.d.ts",
"InterpolateHtmlPlugin.d.ts",
"launchEditor.d.ts",
"ModuleScopePlugin.d.ts",
"noopServiceWorkerMiddleware.d.ts",
"openBrowser.d.ts",
"printBuildError.d.ts",
"printHostingInstructions.d.ts",
"WatchMissingNodeModulesPlugin.d.ts",
"WebpackDevServerUtils.d.ts",
"test/eslintFormatter.ts",
"test/noopServiceWorkerMiddleware.ts",
"test/utils.ts",
"test/webpack-plugins.ts",
"test/webpack-utils.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }