In this exercise, we will introduce Webpack’s rule system and practice defining a rule for dealing with .txt files in our project.

Webpack uses rules to know what to do with different file types. Webpack expects an array of rules in a configuration option called module. The syntax looks like:

module.exports = { module: { rules: [] } }

A rule has a test configuration option defined as a regular expression. If a file matches the regular expression, Webpack will use the rule on that file. For example, if we define test as \.txt$\i, the rule will apply to files ending in .txt.

The other part of the rule needs to tell Webpack what to do with files that match the test. That part of the rule varies by file type.

For .txt files, the rule inside of rules would look like:

rules: [ { test: /\.txt$/i, type: 'asset/source' } ]

Here, type: 'asset/source' is telling Webpack that .txt files are an asset that can be added directly to the source code, not requiring much processing. Once we add a rule for a file type, we can import files of that type into our code. Here’s an example with a .txt file:

import Text from './example.txt'; document.querySelector('h1').innerHTML = Text;

Previewing this code replaces the content of the page h1 element with the file content.

Let’s get some practice defining Webpack rules!



Let’s get ready to add some rules.

In webpack.config.js, add a module configuration option to the module.exports with an empty rules array inside.

Click “Run” when done.


We are ready to write our first rule! Define a rule for .txt files inside the rules array.

Click “Run” when finished.


Let’s bundle some content into our app!

Import the text content at the top of src/index.js as Text and use it where we set the innerHTML of the h1 element (Uncomment and set line 5).


In one terminal run the build command.

Click “Run” when you’ve done it.


Open up another terminal:

Opening up another terminal with the plus button above Run

And run the start command in it.

Click “Run” when you’re done, and refresh the page with the icon on the right.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?