React Native TypeScript Images and Static Assets

I followed in a tutorial that Microsoft released how to convert your ReactNative project to TypeScript.

Everything worked perfectly until I reached the point where I needed to include images in my project. Obviously it tscdoesn't pack images in outdir, so my question is how do people currently use images or other static resources when using ReactNative with TypeScript?

+8
source share
1 answer

Option 1 - Move the image folder to the root of the project:

As I decided to solve the problem, it was necessary to move the images to the root directory of the project, and not live in the directory src.

Create a folder imagesin the root of the project

images/
  - sample-image.jpg
src/
  - App.tsx
output/
  - App.js

Link to image using relative path

const image = require('../images/sample-image.jpg');
...
<Image src={image} style={{ width: 100, height: 100 }} />

Since the output form must match the shape of the source directory, the link to the top-level image directory works just fine.

Option 2 - use copyfilesthe npm package:

This option allows you to keep images embedded, but requires an additional step when restoring your project.

Install copyfiles

npm i -D copyfiles

Add to package.jsonscripts

following:
...
"start": "npm run build && node node_modules/react-native/local-cli/cli.js start",
"build": "npx tsc && npm run add-assets",
"add-assets": "copyfiles -u 1 'src/**/!(*.js|*.jsx|*.map|*.ts|*.tsx)' lib/",
...

Now execute npm run buildor npm start, and our new new package copyfileswill copy any file without a source to the out directory.

. , glob , , outdir.

+3

Source: https://habr.com/ru/post/1694797/


All Articles