React Native新手求助:snack.expo.io中JS文件导入导出报错
Hey there! I’ve run into this exact error dozens of times when working with Expo Snack, and it almost always comes down to incorrect import paths for your local components. Let’s break down how to fix this step by step.
Why This Error Happens
The error mentions ~component1@latest because Expo Snack interprets paths starting with ~ or absolute paths like /component1 as requests to download a public npm package—not your local component1.js file. Since there’s no real npm package named component1, it fails to find what it’s looking for.
Step-by-Step Fixes
1. Use the Correct Relative Import Path
Since your component1.js is in the same directory as App.js (the default setup in Snack), you need to use a relative path starting with ./ to tell Snack it’s a local file.
Wrong Imports (these cause the error):
import Component1 from '/component1'; // OR import Component1 from '~component1';
Correct Imports:
// For default exports in component1.js import Component1 from './component1.js'; // For named exports (e.g., export const Component1 = ...) import { Component1 } from './component1.js';
2. Verify Your Component’s Export
Make sure component1.js has a valid export so App.js can import it. Here’s a simple working example:
component1.js:
import React from 'react'; import { Text, View } from 'react-native'; // Default export (matches the first import example above) export default function Component1() { return ( <View style={{ padding: 15 }}> <Text>Hello from Component1! 🎉</Text> </View> ); }
3. Double-Check File Names & Case
Expo Snack is case-sensitive! If your file is named Component1.js but you import ./component1.js, it will fail. Make sure the import path matches the exact filename (including uppercase/lowercase letters).
4. Confirm File Placement
Ensure component1.js shows up in the Snack file explorer (left sidebar) and is in the same root directory as App.js. If you nested it in a subfolder (like components/), adjust the path accordingly:
import Component1 from './components/component1.js';
Full Working Example
Here’s how your files should look together to resolve the error:
App.js:
import React from 'react'; import { View, StyleSheet } from 'react-native'; import Component1 from './component1.js'; export default function App() { return ( <View style={styles.container}> <Component1 /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, });
component1.js:
import React from 'react'; import { Text } from 'react-native'; export default function Component1() { return <Text>This is my Component1 output!</Text>; }
That should resolve the error and let you see the output from component1.js in your Snack preview.
内容的提问来源于stack exchange,提问作者Jeremiah

