Skip to content

Unitools | Dynamic File Loading | By GeekyAnts

Dynamic File Loading

In the cross-platform development, sharing code for essential functionalities like navigation and image handling across frameworks such as Next.js & Expo presents several challenges:

Code Sharing :

  1. Fragmentation of APIs
  2. Limited Options

To know more about issues with Code Sharing refer this docs.

Module Resolution

In JavaScript-based frameworks, dynamic file loading is a technique used to conditionally load files based on the environment or framework in use. This allows developers to tailor code specifically for different frameworks without modifying the core logic. A common scenario for this is using a file naming convention to allow the appropriate framework to pick the correct file version during runtime or build.

For Next.js & Expo

When working in a project that targets multiple environments like Next.js and Expo, you can use specific file extensions to ensure that the appropriate framework picks the correct file. This can be particularly useful when dealing with platform-specific code differences.

Next.js (*.next-web.js):

When you use the *.next-web.js extension, the Next.js framework will automatically detect and load this specific file. This allows you to write code that is tailored for web-based execution using Next.js. Next.js will prioritize this file when building or serving content for web environments.

index.next-web.js
export const Component = () => {
return <div>This code runs in Next.js (web).</div>;
};

Expo (*.js):

In Expo, which is primarily used for mobile applications (but also supports web), you can use *.js. Expo will recognize this file as the entry point for its environment and will load the code accordingly. This allows you to write code optimized for mobile or Expo-specific environments.

index.js
export const Component = () => {
return <Text>This code runs in Expo (mobile).</Text>;
};

How It Works

Next.js uses a custom Webpack configuration that can recognize files with *.next-web.js extension, ensuring that this code is included during web-specific builds.

Expo follows a similar pattern but defaults to picking files with the *.js extension. This convention ensures that mobile-specific code is prioritized for the Expo environment.

Benefits

  1. Separation of Concerns: You can maintain different logic for different platforms without duplicating code across files.
  2. Framework Optimization: The framework picks only the necessary file based on the environment, optimizing performance.
  3. Simplified Maintenance: By using framework-specific file naming, you can avoid writing complex conditionals or manually switching between environments, making the codebase easier to maintain. This dynamic file loading strategy is especially useful for multi-platform projects, allowing developers to customize behavior without polluting the global code with unnecessary checks.