UNPKG

@redshank/native-router

Version:

@redshank/native-router is a file-based router for React Native CLI

97 lines (85 loc) 2.62 kB
const path = require('path'); const resolveFrom = require('resolve-from'); function getRouterRoot(projectRoot, appDirectory) { if (process.env.ROUTER_ROOT) { return process.env.ROUTER_ROOT; } console.log( `Generating routes for app directory: ${appDirectory} and project root: ${projectRoot}`, ); const isBrowser = typeof window !== 'undefined'; const contextPath = resolveFrom.silent( projectRoot, isBrowser ? '@redshank/native-router/_context.web.tsx' : '@redshank/native-router/_context.native.tsx', ); const routerRoot = path.relative( path.dirname(contextPath), path.join(projectRoot, appDirectory), ); return routerRoot; } function getRedshankConfig() { const projectRoot = process.cwd(); const configPath = path.join(projectRoot, 'redshank.config.js'); let configModule; try { configModule = require(configPath); } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { console.log(`redshank.config.js not found. Using default config.`); } } const config = configModule && configModule.default ? configModule.default : configModule; return config || {}; } module.exports = function autoRoutesPlugin({ types: t }) { return { visitor: { MemberExpression(p) { if ( !t.isIdentifier(p.node.object, { name: 'process' }) || !t.isIdentifier(p.node.property, { name: 'env' }) ) { return; } const parent = p.parentPath; if (!t.isMemberExpression(parent.node)) { return; } const redshankConfig = getRedshankConfig(); const appDirectory = redshankConfig?.appDirectory || 'app'; const importMode = redshankConfig?.importMode || 'sync'; const root = redshankConfig?.root || ''; if ( t.isIdentifier(parent.node.property, { name: 'APP_DIRECTORY', }) && !parent.parentPath.isAssignmentExpression() ) { parent.replaceWith(t.stringLiteral(appDirectory)); } if ( t.isIdentifier(parent.node.property, { name: 'ROUTER_ROOT', }) && !parent.parentPath.isAssignmentExpression() ) { parent.replaceWith( t.stringLiteral(getRouterRoot(root, appDirectory)), ); } if ( t.isIdentifier(parent.node.property, { name: 'IMPORT_MODE', }) && !parent.parentPath.isAssignmentExpression() ) { parent.replaceWith(t.stringLiteral(importMode)); } }, }, }; };