⚠️ FYI:The approach demonstrated in this article is not the optimal solution, and the author does not recommend using AST to automatically generate React Native routes, as working with Babel is relatively complex and prone to errors. Instead, the author suggests using template strings. The main purpose of this article is to verify the feasibility of using AST for automatic route generation, rather than to serve as a best practice guide.
In React Native, you cannot use routing management tools like React Router
or Wouter
that are based on the browser environment because React Native itself doesn't run in a browser environment, so it lacks browser DOM or BOM APIs. Therefore, you need to use React Navigation
, which utilizes system-level native APIs to create and manage screens (Activity in Android and UIView in iOS).
When using React Navigation
, you need to manually declare each page using Stack.Screen
. It cannot automatically generate routing tables like frameworks such as umi
or next.js
through convention-based routing or routing declaration files. This is because the JavaScript in React Native doesn't run on node.js
; it's just a simple runtime environment.
For this practice, you'll use the following third-party code:
https://github.com/isaacs/node-glob
@babel/plugin-transform-react-jsx
In most React Native projects, page file paths and naming conventions are standardized. For this article, we'll use the /pages/${page-name}/index
naming convention.
We'll use the npm package glob
to match files. glob
is chosen as the file search tool because it supports wildcards and regex-like expressions, making it more efficient than using fs
operations.
glob(
path.resolve(__dirname, './pages/*/?(index|index.android|index.ios).tsx'),
(error, files) => {
if (error) {
return
}
}
)
Based on the naming convention above, the matching pattern is './pages/*/?(index|index.android|index.ios).tsx'
. index.android
and index.ios
are files with different extensions selected by React Native based on the build target. For more details, refer to:
Platform Specific Code · React Native
After the first step, you'll have the absolute paths of all page files, such as:
/react-native-project/src/pages/home/index.tsx
/react-native-project/src/pages/login/index.tsx
/react-native-project/src/pages/order-info/index.tsx
Now, you need to write a regex to extract the page names, i.e., Home
, Login
, and OrderInfo
.