React Native TypeScript Images &静态资产 [英] React Native TypeScript Images & Static Assets

查看:44
本文介绍了React Native TypeScript Images &静态资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注微软发布的教程将您的 ReactNative 项目转换为 TypeScript.

I was following along in the tutorial that Microsoft put out on how to convert your ReactNative project to TypeScript.

一切都很好,直到我需要在我的项目中包含图像.显然 tsc 不会将图像打包到 outdir 中,所以我的问题是当使用 ReactNative 和 TypeScript 时,人们目前如何使用图像或其他静态资产?

Everything worked great until I reached the point where I needed to include images in my project. Obviously tsc doesn't pack up images into the outdir, so my question is how are people currently using images or other static assets when using ReactNative with TypeScript?

推荐答案

选项 1 - 将图像文件夹移动到项目的根目录:

我最终解决问题的方法是将图像移动到项目的根目录,而不是在 src 目录中.

images/
  - 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.

此选项允许您保持图像内联,但在重建项目时需要额外的步骤.

This option allows you to keep images inline, but requires an extra step when rebuilding your project.

npm i -D copyfiles

...
"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/",
...

现在执行 npm run buildnpm start 和我们漂亮的新包 copyfiles 将复制任何非源文件到 out 目录.

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.

注意:您可能需要根据需要更新 glob 以忽略您不想复制到 outdir 的文件.

NOTE: You may need to update the glob as needed to ignore files that you do not want copied over to the outdir.

这篇关于React Native TypeScript Images &amp;静态资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆