首页 文章

无法从React Native App中的项目文件夹导入.js文件

提问于
浏览
2

我无法从我的项目文件夹(节点模块,如'react','react-native'工作正常)导出模块到我的App.js文件 . 我使用create-react-native-app创建了一个新项目,并尝试了以下方法:

  • 将test_file.js添加到我的项目文件夹中 .

  • 在test_file中我声明了变量 test 然后将其导出 .

  • 然后我将它导入我的App.js并运行 npm start .

一切似乎没事,直到我尝试通过世博会运行它 . JavaScript捆绑包构建失败,在我的手机中它会显示错误消息: The development server returned response error code: 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.清除守望者 Watch :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 . 删除haste chache:`rm -rf / Test /急速 Map 反应的母语 - 打包 - ' . “

到目前为止,我已经尝试了所有四种方法,并查看了提供的链接,但尚未找到解决方案 . 我也尝试使用 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',
  },
});

1 回答

  • 1

    我们必须在import语句中提到路径 .

    如果文件在同一个文件夹中:

    import test from './test_file';
    

    如果文件位于以前的文件夹或子文件夹中:

    import test from '../test_file';
    

相关问题