【问题标题】:Can't import .js files from project folder in React Native App无法从 React Native App 的项目文件夹中导入 .js 文件
【发布时间】:2018-11-26 02:59:19
【问题描述】:

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

  1. 已将 test_file.js 添加到我的项目文件夹中。
  2. 在 test_file 中,我声明了变量 test,然后将其导出。
  3. 然后我将它导入到我的 App.js 并运行 npm start

在我尝试通过 expo 运行它之前,一切似乎都很好。 JavaScript 包构建失败,在我的手机中它给出了一条错误消息:The development server returned response error code: 500

还有一条消息:"Unable to resolve module `test_file` from `C:\Users\User\Projects\Test\App.js`: Module `test_file` does not exist in the Haste module map \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 . 移除急速缓存:`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',
  },
});

【问题讨论】:

  • 请添加代码以便检查

标签: javascript react-native import


【解决方案1】:

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

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

import test from './test_file';

如果文件在前一个文件夹或子文件夹中:

import test from '../test_file';

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 2021-04-14
    • 2018-10-10
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多