Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Plugins and Assets

Define, Copy and Clean Plugins

Use everyday Webpack plugins: DefinePlugin and EnvironmentPlugin for build-time constants, dotenv for env files, CopyWebpackPlugin for static files, ProvidePlugin, and output.clean.

Three small jobs come up in nearly every project: injecting constants such as an API URL, copying files that are not imported anywhere (robots.txt, favicons), and cleaning the output folder. This lesson covers the plugins and options for them, plus a few other built-in plugins you will meet.

DefinePlugin: constants replaced at build time

DefinePlugin is built into Webpack. It replaces identifiers in your code with values while building, which is how process.env.NODE_ENV works (Build Modes).

JavaScript
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      API_URL: JSON.stringify('https://api.example.com'),
      DEBUG: false,
      'process.env.APP_VERSION': JSON.stringify(require('./package.json').version),
    }),
  ],
};

The crucial rule: the value is inserted as code text. A string must be wrapped in JSON.stringify (or double-quoted inside single quotes), otherwise API_URL: 'https://...' becomes bare, invalid code. Numbers and booleans go in as they are.

JavaScript
// your source
fetch(API_URL + '/users');
if (DEBUG) { console.log('debug'); }
// after the build
fetch("https://api.example.com" + '/users');
if (false) { console.log('debug'); }   // removed by the minifier

Because the replacement is textual, there is no runtime object: console.log(process.env) still fails in the browser. Also never put secrets here: whatever you define ships to every user who opens DevTools.

Node.js Stand-in: how DefinePlugin substitutes text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

EnvironmentPlugin and .env files

EnvironmentPlugin is a shortcut for defining process.env.X values read from the real environment, with optional defaults:

JavaScript
new webpack.EnvironmentPlugin({
  API_URL: 'http://localhost:3000',   // default if the variable is not set
  FEATURE_FLAGS: null,                 // null means "required": warn if missing
})

Run API_URL=https://api.example.com webpack --mode production and the code sees that value. To load variables from a .env file, use dotenv-webpack (or dotenv in your config), and pass only variables you intend to be public. Build-time values are baked in: changing them requires a rebuild.

CopyWebpackPlugin: static files

Files such as robots.txt, _redirects, favicons or a public/ folder are not imported by any module, so Webpack never sees them. copy-webpack-plugin copies them to the output.

Terminal
npm install --save-dev copy-webpack-plugin
JavaScript
const CopyPlugin = require('copy-webpack-plugin');

plugins: [
  new CopyPlugin({
    patterns: [
      { from: 'public', to: '.', globOptions: { ignore: ['**/index.html'] } },
      { from: 'node_modules/pdfjs-dist/build/pdf.worker.min.js', to: 'vendor/' },
    ],
  }),
],

from can be a file, folder or glob; to is relative to output.path. Ignore index.html when HtmlWebpackPlugin generates it, or you will have two competing files. Copied files are not part of the graph, so they get no hash: give them stable names deliberately.

Node.js Stand-in: copy files matching patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Cleaning the output folder

Old hashed files pile up in dist otherwise. Webpack 5 has it built in:

JavaScript
output: { clean: true },
// or keep some files
output: { clean: { keep: /\.git\// } },

The older clean-webpack-plugin is no longer needed. In webpack serve, output is served from memory, so cleaning only matters for real builds.

ProvidePlugin and IgnorePlugin

  • ProvidePlugin makes a module available as a free variable without importing it: new webpack.ProvidePlugin({ $: 'jquery', process: 'process/browser' }). It is useful for legacy libraries and Node-style polyfills, but explicit imports are clearer in new code.
  • IgnorePlugin skips optional imports, for instance moment locales: new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }).
  • BannerPlugin adds a comment such as a license line to the top of each bundle.
flowchart LR
  S["Source + imports"] --> G["Graph"]
  G --> D["DefinePlugin: constants"]
  G --> O["Output files"]
  C["CopyPlugin: static files"] --> O
  K["output.clean: tidy dist"] --> O

Plugins act on the graph or add files to the output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must string values for DefinePlugin be wrapped in JSON.stringify?

    Without quotes the replacement would be bare text and produce invalid or wrong code.
  2. 2. Why should secrets not be put into DefinePlugin or EnvironmentPlugin?

    Anything replaced at build time becomes visible in the shipped JavaScript.
  3. 3. Which option replaces clean-webpack-plugin in Webpack 5?

    output.clean: true empties the output directory before emitting.
  4. 4. Why does a file copied with CopyWebpackPlugin have no content hash?

    Copied files bypass the graph; add hashes yourself or rely on cache headers and versions.

Summary

  • DefinePlugin swaps identifiers for code text at build time; stringify strings and never ship secrets.
  • EnvironmentPlugin and dotenv expose environment values with defaults; changes need a rebuild.
  • CopyWebpackPlugin copies files outside the graph; avoid duplicating the generated HTML.
  • output.clean keeps dist tidy.
  • ProvidePlugin, IgnorePlugin and BannerPlugin cover legacy globals, optional imports and banners.

Next: Writing a Plugin