Learn

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!

Instructions

1.

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.

2.

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

Click “Run” when finished.

3.

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.

4.

In one terminal run the build command.

Click “Run” when you’ve done it.

5.

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.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?