@vizworx/webpack-starter
v5.1.1
Published
A collection of sane defaults for Webpack
Readme
Webpack Starter
Setting up a fresh Webpack configuration can be overwhelming, even when following a start-to-finish guide like SurviveJS - Webpack. We have compiled a set of sane defaults that can be customized in order to bootstrap new and existing projects.
If you are upgrading to v4 or v5, please see our migration guide.
Minimal Setup
To start using this project, install the package and set up your webpack.config.babel.js to customize the default configuration.
npm install --save-dev @vizworx/webpack-starternpm install --save-dev @pmmmwh/react-refresh-webpack-plugin react-refreshwebpack.config.babel.js
import webpackStarter from '@vizworx/webpack-starter';
export default webpackStarter({
html: { title: 'My Webpack Project' },
});Configuration
Many of the parts can be configured through the webpackStarter function, using the options listed in their section.
import webpackStarter from '@vizworx/webpack-starter';
export default webpackStarter({
html: {
title: 'My Webpack Project'
meta: {
robots: 'noindex, nofollow',
},
},
react: true,
hot: true,
development: {
port: 3000,
},
production: {
lazyChunks: true,
},
});If you pass { react: false } or { hot: false }, you do not need the @pmmmwh/react-refresh-webpack-plugin or
react-refresh dependencies.
Webpack Middleware
If you are using the webpack-dev-middleware with Express, you can use addStarterMiddleware to automatically add the appropriate middleware and hot reload support.
import express from 'express';
import path from 'path';
const app = express();
const publicFolder = path.resolve(__dirname, '../client');
app.use(express.static(publicFolder));
if (process.env.NODE_ENV !== 'development') {
app.get('*', (req, res) => res.sendFile(path.resolve(publicFolder, 'index.html')));
} else {
/* eslint-disable global-require, import/no-extraneous-dependencies */
// To prevent these from loading in production, we need to use a scoped require
const { addStarterMiddleware } = require('@vizworx/webpack-starter');
const webpackConfig = require('../../webpack.config.babel').default;
addStarterMiddleware(app, webpackConfig);
/* eslint-enable global-require, import/no-extraneous-dependencies */
}
// eslint-disable-next-line no-console
app.listen(3000, () => console.log(`Listening on http://localhost:3000 (${process.env.NODE_ENV})`));Routing
This option will register GET * (or GET yourEntryPointFolder/* if you have multiple entrypoints) with the Express app to serve Webpack's generated index.html. Any other GET routes must be registered prior to running addStarterMiddleware as any GET route added afterward will be inaccessible.
Parts
The configuration has been split into multiple parts, that can be used via the webpackStarter function, or used manually by passing an array of parts into webpack-merge (SurviveJS - Webpack explains this in detail).
import merge from 'webpack-merge';
import * as parts from '@vizworx/webpack-starter';
export default merge([
parts.common(),
parts.babel({ react: false }),
parts.html({ title: 'Hello World' }),
(process.env.NODE_ENV ==='development')
? parts.development({ port: 3000 })
: parts.production(),
]);babel
The babel part will set up babel-loader to process .js files, and can optionally add support for .jsx as well.
Options
react(boolean): Enables the.jsxextensionhot(boolean): Enables hot-reloading of ReactfullySpecified(boolean:false): Require modules to fully specify extensionsbabel(object): Options that are passed tobabel-loader
common
The common part will set up a default entrypoint, output names, extensions, and the CaseSensitivePathsPlugin.
development
The development part will set the Webpack mode to development, enable the (cheap-module-eval-source-map devtool)[https://webpack.js.org/configuration/devtool/], and enable the devServer.
All options that are provided will be passed through to the devServer. The default is to use the HOST and PORT environment variables and to rewrite all missing paths to /index.html to support Single Page Applications.
fonts
The fonts part will automatically process woff, woff2, ttf, otf, and eot. Any files smaller than 8KB will be converted to Base64 and inlined, and the rest will be output in the fonts folder.
Options
staticPath(string): The path (without the leading slash) that the fonts should be loaded from (eg.static)
gitRevision
The gitRevision part will inject the current git commit hash (and tag if there is one) into the header of every generated chunk. This simplifies the process of associating a compiled chunk to the code it was built from. This can be disabled by passing { gitRevision: false } in the webpackStarter argument.
html
The html part uses a tweaked version of the html-webpack-plugin template.
Options
In addition to the standard html-webpack-plugin options, you can also use:
extraHead(stringor[string]): HTML to add into the<head>of the templateextraBody(stringor[string]): HTML to add to the end of the<body>of the template
images
The images part will add support for loading svg, gif, jpg, jpeg, and png from JS and CSS. If the file is smaller than 8KB, it will be converted to Base64 and inlined.
Options
staticPath(string): The path (without the leading slash) that the images should be loaded from (eg.static)
production
The production part will set the Webpack mode to production, and enable the CleanWebpackPlugin and ManifestPlugin. It can also set up some common defaults for code-splitting and lazy-loading chunks.
Options
lazyChunks(booleanorobject): This will enable some generic vendor chunk optimizations for code splitting and lazy loading. It assumes that you have set up multiple code-splits and will attempt to keep async vendors in a shared file.minSize(number): The minimum size (bytes) required before a new vendor chunk will be createdmaxSize(number): The maximum size (bytes) that a vendor chunk may be before it is split in half
clean(object): This will be passed to clean-webpack-pluginmanifest(object): This will be passed to webpack-manifest-plugin
react
The react part adds support for hot-reloading components optionally with hooks, the react flag is set to true by default.
Options
entry: See Entry Points for optionshot(booleanorobject): Enables the hot-reloading option and adds hooks support for hot-reloading. To enable this option make sure to:npm install --save-dev @pmmmwh/react-refresh-webpack-plugin react-refresh- Include the
fast-refresh/babelplugin only in development.
const isDevelopment = process.env.NODE_ENV !== 'production';
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: isDevelopment ? ['react-refresh/babel'] : [],
};reactSVG
The reactSVG part will allow JS/JSX files to automatically convert svg files into React components, via @svgr/webpack.
styles
The styles part will add support for CSS, PostCSS, and optionally Sass, for both development and production. It does not provide a PostCSS configuration by default, allowing you to add your own postcss.config.js.
Options
extract(boolean): Should the compiled CSS be extracted into acssfile that is added to the<head>postcss(booleanorobject:true): Should PostCSS be used. If passed an object, it will be passed to the postcss-loadersass(booleanorobject:false): Should Sass be used to compile.sass,.scss, and.cssfiles. If passed an object, it will be passed to the sass-loader, which you will need to install.
