Search code examples
javascriptreact-nativetensorflowrequiretensorflow.js

React Native importing error: unable to resolve module with .bin (how to import a certain type of file?)


I am receiving an error when running a react native application.

Unable to resolve "./tfjs_model_to_use_quantized/content/tfjs_model_to_use/group1-shard1of1.bin" from "components\ImageInput.js"

I am attempting to import a file called group1-shardof1.bin in my JS code.

Other require functions (for example, for a json file) are working fine, and the file path for this specific require function is correct. I thought the problem would be that the .bin extension was not supported for exporting in react native Code:

const modelWeights = require('./tfjs_model_to_use_quantized/content/tfjs_model_to_use/group1-shard1of1.bin')

What I have tried, I added:

"packagerOpts": {
      "assetExts": ["bin", "pb", "txt"]
}

in my app.json, with the bin extension.

How can I configure my react-native application to be able to import a .bin file extension into a JS file? It would be great if anyone can help me with this issue.


Solution

  • I found an answer. Additional file types to be resolved by react native can be configured in metro.config.js:

    const blacklist = require('metro-config/src/defaults/blacklist');
    module.exports = {
      transformer: {
        getTransformOptions: async () => ({
          transform: {
            experimentalImportSupport: false,
            inlineRequires: false,
          },
        }),
      },
      resolver: {
        // (add 'bin' to assetExts)
        assetExts: ['bin', 'txt', 'jpg', 'png', 'ttf'],
        sourceExts: ['js', 'json', 'ts', 'tsx', 'jsx'],
        blacklistRE: blacklist([/platform_node/])
      },
    };
    

    The key portion is the assetExts part, adding "bin" to the list. In my specific case, there was no metro.config.js file created for some reason, but I created a new file with the above code, and the import of .bin worked fine.