Skip to content
This repository was archived by the owner on Jan 26, 2019. It is now read-only.

Documented how to define custom module formats for the TypeScript compiler so that you can import images and other files #231

Merged
merged 1 commit into from
Jan 20, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions packages/react-scripts/template/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -623,11 +623,26 @@ Now running `npm start` and `npm run build` also builds Sass files.

With Webpack, using static assets like images and fonts works similarly to CSS.

You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.
You can **`import` a file right in a TypeScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.

To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153).

Here is an example:
Before getting started, you must define each type of asset as a valid module format. Otherwise, the TypeScript compiler will generate an error like this:

>Cannot find module './logo.png'.

To import asset files in TypeScript, create a new type definition file in your project, and name it something like `assets.d.ts`. Then, add a line for each type of asset that you need to import:

```ts
declare module "*.gif";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.png";
```

In this case, we've added several image file extensions as valid module formats.

Now that the compiler is configured, here is an example of importing an image file:

```js
import React from 'react';
Expand Down