0

I have a TypeScript module that uses Lua code from an external .lua file to do some adapter magic. I include this Lua code stringified in the JavaScript and then use 'lua-in-js' package to execute it. I use the 'fs' module to read the file with fs.readFileSync and then I stringify the result like this. (See module.ts below.)

const luaCode = fs.readFileSync('./adapter.lua').toString()

However, the challenge is that this TypeScript module is used in React Native, where the 'fs' package is not supported. I use 'tsc' to compile the module bundle, but in the compiled code, the 'fs' module is included and used as a dependency. (See bundle.js below.)

const fs_1 = require("fs");

const luaCode = (0, fs_1.readFileSync)('./adapter.lua').toString();

When trying to run the code it crashes because 'fs' is not supported in RN. So the Lua code would have to be included in the bundle file in its entirety inside the string variable luaCode. How can I achieve this? Below is also my tsconfig.json for reference.

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "declaration": true,
    "outDir": "lib",
    "strict": true,
    "removeComments": true,
    "skipLibCheck": true,
    "isolatedModules": true
  },
    "include": [
    "src/**/*"
  ]
}

1 Answer 1

0

I found the solution eventually by myself. I changed the build process to use Babel, leaving 'tsc' to only generate type declarations. (See build script in package.json below.)

"build": "babel src --out-dir lib --extensions .ts && tsc",

I installed the Babel plugin 'babel-plugin-inline-import' and 'babel-plugin-module-resolver', of which the former lead to the result what I wanted. For compiling I used the preset '@babel/preset-typescript'. (See babel.config.js below.)

module.exports = {
    presets: ['@babel/preset-typescript'],
    plugins: [
        [
            'babel-plugin-inline-import',
            {
                extensions: ['.lua']
            }
        ]
    ],
    env: {
        test: {
            plugins: ['@babel/plugin-transform-modules-commonjs']
        }
    }
};

Below is also my updated tsconfig.json for reference.

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "declaration": true,
    "outDir": "lib",
    "strict": true,
    "removeComments": true,
    "skipLibCheck": true,
    "emitDeclarationOnly": true,
    "isolatedModules": true,
    "moduleResolution": "node",
  },
    "include": [
    "src/**/*"
  ]
}

After these were configured, I could simply import the Lua file in the TypeScript module and use it in 'lua-in-js'.

import luaAdapter from './adapter.lua';
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.