无法在React Native应用程序中从项目文件夹导入.js文件

3
我在将项目文件夹中的模块(例如'react','react-native'等npm模块)导出到我的App.js文件时遇到了麻烦。我使用create-react-native-app创建了一个新项目,并尝试了以下操作:
  1. 将test_file.js添加到我的项目文件夹中。
  2. 在test_file中声明变量 test ,然后将其导出。
  3. 然后我将其导入到我的App.js中并运行 npm start
一切似乎都很好,直到我尝试通过expo运行它。JavaScript捆绑构建失败,在我的手机上显示错误消息:开发服务器返回响应错误代码:500
还有一条消息:"无法从'C:\ Users \ User \ Projects \ Test \ App.js'解析模块'test_file':模块'test_file'不存在于Haste模块映射中\n\n这可能与 https://github.com/facebook/react-native/issues/4968 有关\n要解决问题,请尝试以下操作:\n 1.清除watchman观察:'watchman watch-del-all'。\n 2.删除“node_modules”文件夹:'rm -rf node_modules&&npm install'。\n 3.重置Metro Bundler缓存:'rm-rf /Test/metro-bundler-cache- '或'npm start --reset-cache'。 4.删除急切的cach:`rm -rf /Test/haste-map-react-native-packager-`。

到目前为止,我已经尝试了所有四种方法并查看了提供的链接,但还没有找到解决方案。我还尝试使用 require 而不是 import
是什么导致这个问题呢?
编辑:以下是测试代码:
test_file.js:
const test = 'Hello World.';

export default test;

App.js:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import test from 'test_file';


export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>{test}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

请添加代码以便进行检查。 - user3210641
1个回答

2
我们必须在导入语句中提及路径。如果文件与当前文件位于同一文件夹中:
import test from './test_file';

如果文件在上一级文件夹或子文件夹中:
import test from '../test_file';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接