@computerrock/react-dev-utils
v2.0.0
Published
Webpack utilities for React projects
Downloads
176
Keywords
Readme
@computerrock/react-dev-utils
This package contains Webpack utilities used for React projects. It is based on Create React App package.
Usage
Install package by running:
$ npm install @computerrock/react-dev-utils --save-dev
There is no single entry point. You can only import individual top-level modules:
const ModuleScopePlugin = require('@computerrock/react-dev-utils/ModuleScopePlugin');
new InterpolateHtmlPlugin(replacements: {[key:string]: string})
This Webpack plugin lets us interpolate custom variables into index.html
.
It works in tandem with HtmlWebpackPlugin 2.x via its
events.
var path = require('path');
var HtmlWebpackPlugin = require('html-dev-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
// Webpack config
const publicPath = '/my-custom-url';
module.exports = {
output: {
// ...
publicPath: publicPath + '/'
},
// ...
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: path.resolve('public/index.html'),
}),
// Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
new InterpolateHtmlPlugin({
PUBLIC_URL: publicPath
// You can pass any key-value pairs, this was just an example.
// WHATEVER: 42 will replace %WHATEVER% with 42 in index.html.
}),
// ...
],
// ...
}
new ModuleScopePlugin(appSrc: string | string[], allowedFiles?: string[])
This Webpack plugin ensures that relative imports from app's source directories don't reach outside of it.
var path = require('path');
var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
module.exports = {
// ...
resolve: {
// ...
plugins: [
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
// ...
],
// ...
},
// ...
}
new WatchMissingNodeModulesPlugin(nodeModulesPath: string)
This Webpack plugin ensures npm install <library>
forces a project rebuild.
See #186 for details.
var path = require('path');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
// Webpack config
module.exports = {
// ...
plugins: [
// ...
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(path.resolve('node_modules'))
],
// ...
}
checkRequiredFiles(files: Array<string>): boolean
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
.
var path = require('path');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
if (!checkRequiredFiles([
path.resolve('public/index.html'),
path.resolve('src/index.js')
])) {
process.exit(1);
}
clearConsole(): void
Clears the console, hopefully in a cross-platform way.
var clearConsole = require('react-dev-utils/clearConsole');
clearConsole();
console.log('Just cleared the screen!');
eslintFormatter(results: Object): string
This is custom ESLint formatter that integrates well with Create React App console output. You can use the default one instead if you prefer so.
const eslintFormatter = require('react-dev-utils/eslintFormatter');
// In your webpack config:
// ...
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
enforce: 'pre',
use: [
{
loader: 'eslint-loader',
options: {
// Pass the formatter:
formatter: eslintFormatter,
},
},
],
}
]
}
FileSizeReporter
measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>
Captures JS and CSS asset sizes inside the passed buildFolder
. Save the result value to compare it after the build.
printFileSizesAfterBuild(webpackStats: WebpackStats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number)
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).
var {
measureFileSizesBeforeBuild,
printFileSizesAfterBuild,
} = require('react-dev-utils/FileSizeReporter');
measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => {
return cleanAndRebuild().then(webpackStats => {
printFileSizesAfterBuild(webpackStats, previousFileSizes, buildFolder);
});
});
formatWebpackMessages({errors: Array<string>, warnings: Array<string>}): {errors: Array<string>, warnings: Array<string>}
Extracts and prettifies warning and error messages from webpack stats object.
var webpack = require('webpack');
var config = require('../config/webpack.config.dev');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var compiler = webpack(config);
compiler.hooks.invalid.tap('invalid', function() {
console.log('Compiling...');
});
compiler.hooks.done.tap('done', function(stats) {
var rawMessages = stats.toJson({}, true);
var 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));
}
});
printBuildError(error: Object): void
Prettify some known build errors. Pass an Error object to log a prettified error message in the console.
const printBuildError = require('react-dev-utils/printBuildError')
try {
build()
} catch(e) {
printBuildError(e) // logs prettified message
}
getProcessForPort(port: number): string
Finds the currently running process on port
.
Returns a string containing the name and directory, e.g.,
create-react-app
in /Users/developer/create-react-app
var getProcessForPort = require('react-dev-utils/getProcessForPort');
getProcessForPort(3000);
css-loader
- getLocalBEMIdent()
Use with css-loader
in module mode to ensure BEM class names based on file name (Block) and local class
name (Element/Modifier):
{
loader: require.resolve('css-loader'),
options: {
modules: true,
localIdentName: '[bem]---[contenthash:8]',
getLocalIdent: getLocalBEMIdent,
}
}
WebpackDevServerUtils
choosePort(host: string, defaultPort: number): Promise<number | null>
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 can’t present user
with the choice, resolves to null
.
createCompiler(webpack: Function, config: Object, appName: string, urls: Object, useYarn: boolean): WebpackCompiler
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.
prepareProxy(proxySetting: string, appPublicFolder: string): Object
Creates a WebpackDevServer proxy
configuration object from the proxy
setting in package.json
.
prepareUrls(protocol: string, host: string, port: number): Object
Returns an object with local and remote URLs for the development server. Pass this object to createCompiler()
described above.