如何在React Native中导入sequelize库?

时间:2017-11-07 03:05:52

标签: reactjs react-native sequelize.js

我在react-native项目中使用https://github.com/sequelize/sequelize和sqlite。但安装后,我导入

import Sequelize from 'sequelize';

并运行项目我收到此错误。请帮忙!谢谢。

enter image description here

2 个答案:

答案 0 :(得分:0)

我使用react-native init设置了一个快速演示应用来试试自己。我得到了同样的错误。

在您的浏览器中,打开您的捆绑包URL并且您会更清楚地看到错误。 http://packager.e3-nmz.tuanbaros.demo-sqlite.exp.direct/node_modules/react-native-scripts/build/bin/crna-entry.bundle?platform=android&dev=true&strict=false&minify=false&hot=false&assetPlugin=/home/nguyen.thanh.tuan/Downloads/learning/react-native/demo-sqlite/mode_module/expo/tools/hashAssetFiles

这是错误的关键部分......

TransformError: [...]/node_modules/sequelize/lib/sequelize.js: require() must have a single string literal argument

我不确定这意味着什么,但是打包者在解析续集包本身时遇到了问题。我建议你用sequelize repo打开一个问题。

仅供参考,这里是我编写的代码来测试...

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

import Sequelize from 'sequelize';

export default class App extends Component<{}> {

  state = {
    connection: 'not yet connected'
  }

 componentDidMount() {
   const sequelize = new Sequelize('database', 'username', 'password', {
     host: 'localhost',
     dialect: 'sqlite',
     pool: {
       max: 5,
       min: 0,
       acquire: 30000,
       idle: 10000
     },

     storage: ':memory:'
   });

   sequalize
    .authenticate()
    .then( () => {
      this.setState({ connection: 'Success: SQLite Connection'});
    })
    .catch( err => {
      this.setState({ connection: 'Error: ${err}'})
    });
 }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Let's try to sequelize, shall we?
        </Text>
        <Text style={styles.instructions}>
          {this.state.connection}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

答案 1 :(得分:0)

从React Native 0.49+中,require指令只接受字符串文字。 Sequelize构建了动态需要的参数,这就是为什么你得到你看到的错误。许多图书馆都存在此问题:https://github.com/facebook/react-native/issues/16216

您可以尝试恢复到0.48.4,因为它没有此限制。