React Native TypeScript Images & Static Assets

前端 未结 2 1682
天命终不由人
天命终不由人 2021-02-14 12:36

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-14 12:56

    Option 1 - Move images folder to root of project:

    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.

    Create an images folder in the project root

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

    Reference the image using relative path

    const image = require('../images/sample-image.jpg');
    ...
    
    

    Since the shape of the output should match the shape of the source directory, referencing a top-level image directory works just fine.

    Option 2 - Use copyfiles npm package:

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

    Install copyfiles

    npm i -D copyfiles

    Add the following to 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.

提交回复
热议问题