Merge pull request #231 from joshtynjala/import-images-docs

Documented how to define custom module formats for the TypeScript compiler so that you can import images and other files
This commit is contained in:
Christian Linne
2018-01-20 12:58:15 +01:00
committed by GitHub

View File

@@ -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';