I was following along in the tutorial that Microsoft put out on how to convert your ReactNative project to TypeScript.
Everything worked great until I reached the point
The way I ended up solving the problem was to move the images up to the root dir of the project, rather than living within the src
directory.
images
folder in the project rootimages/
- sample-image.jpg
src/
- App.tsx
output/
- App.js
const image = require('../images/sample-image.jpg');
...
<Image src={image} style={{ width: 100, height: 100 }} />
Since the shape of the output should match the shape of the source directory, referencing a top-level image directory works just fine.
copyfiles
npm package:This option allows you to keep images inline, but requires an extra step when rebuilding your project.
copyfiles
npm i -D copyfiles
package.json
scripts...
"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 build
or npm start
and our nice new package copyfiles
will copy over any non-source file to the out directory.
NOTE: You may need to update the glob as needed to ignore files that you do not want copied over to the outdir.
I'am not sure if this is the best approach,the way I solved it is,
Create a file in the root folder containing images(Should be read by typescript) or any other folder as per your folder structure. Name it "your-name-here.d.ts" (d.ts should be the extension.Its used by typescript engine)
declare module '*.jpg' {
import { ImageSourcePropType } from 'react-native';
const value: ImageSourcePropType;
export default value;
}
ImageSourcePropType is the type expected by the source argument in Image
Now where ever an image is used can be used as
import SampleIcon from '../images/sample-image.jpg';
<Image src={SampleIcon} style={{ width: 100, height: 100 }} />