我有一个现有的 React 本机应用程序。我想创建另一个并在它们之间共享一些代码。我利用 MetroextraNodeModules
将共享代码导入到任一应用程序中。在任一应用程序中,我希望能够执行以下操作:
// MyApp1/src\navigation\app.navigator.js
import { someUtilModule } from 'shared';
不幸的是,当我的开发设备上加载应用程序包时,它失败了:
error: Error: Unable to resolve module `shared` from `src\navigation\app.navigator.js`: shared could not be found within the project or in these directories:
C:\path\to\my\project
If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules: rm -rf node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*
at ModuleResolver.resolveDependency (C:\path\to\my\project\MyApp1\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:186:15)
at ResolutionRequest.resolveDependency (C:\path\to\my\project\MyApp1\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:52:18)
at DependencyGraph.resolveDependency (C:\path\to\my\project\MyApp1\node_modules\metro\src\node-haste\DependencyGraph.js:287:16)
at Object.resolve (C:\path\to\my\project\MyApp1\node_modules\metro\src\lib\transformHelpers.js:267:42)
at C:\path\to\my\project\MyApp1\node_modules\metro\src\DeltaBundler\traverseDependencies.js:434:31
at Array.map (<anonymous>)
at resolveDependencies (C:\path\to\my\project\MyApp1\node_modules\metro\src\DeltaBundler\traverseDependencies.js:431:18)
at C:\path\to\my\project\MyApp1\node_modules\metro\src\DeltaBundler\traverseDependencies.js:275:33
at Generator.next (<anonymous>)
at asyncGeneratorStep (C:\path\to\my\project\MyApp1\node_modules\metro\src\DeltaBundler\traverseDependencies.js:87:24)
文件夹结构(shared
文件夹存在 - 这是来自 的输出tree
):
C:\path\to\my\project
├── MyApp1
│ └── src
│ ├── app
│ ├── assets
│ ├── components
│ ├── core
│ ├── navigation
│ ├── scenes
│ └── services
├── MyApp2
│ └── src
│ ├── app
│ ├── assets
│ ├── components
│ ├── core
│ ├── navigation
│ ├── scenes
│ └── services
└── shared
├── assets
├── components
├── navigation
├── scenes
└── services
我的地铁配置:
// ...
const sharedDir = path.resolve(`${__dirname}/../shared`);
const extraNodeModules = {
shared: sharedDir,
};
const watchFolders = [sharedDir];
module.exports = {
transformer: /*...*/,
resolver: {
extraNodeModules: new Proxy(extraNodeModules, {
get: (target, name) => {
// redirects dependencies referenced from shared/ to local node_modules
return name in target
? target[name]
: path.join(process.cwd(), `node_modules/${name.toString()}`);
},
}),
},
watchFolders,
}