From 934fb112a448dbd766e03c15ebd23cd26968e3c2 Mon Sep 17 00:00:00 2001 From: Josh Tynjala Date: Thu, 18 Jan 2018 10:31:39 -0800 Subject: [PATCH] Documented how to define custom module formats for the TypeScript compiler so that you can import images and other files (references #172) --- packages/react-scripts/template/README.md | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/react-scripts/template/README.md b/packages/react-scripts/template/README.md index c57a0ebd7..6f0338d7e 100644 --- a/packages/react-scripts/template/README.md +++ b/packages/react-scripts/template/README.md @@ -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';