ES6 |如何在这里导出+导入对象?

时间:2019-02-04 08:48:36

标签: node.js reactjs ecmascript-6 import export

我是ES6 +新手,我目前正在构建React应用,但遇到了一个问题-我试图导入2个对象,但未能这样做。我尝试了各种事情并遇到了错误,当我一次尝试都没有遇到错误时,我尝试.toString()对象的属性之一的值并得到undefined的错误。

这是文件结构(忽略不相关的文件):

src
├── index.js
└── style
    └── colors.js

colors.js在哪里:

const primaryColor = {
    900: "#001a8f",
    800: "#002EA2",
    700: "#1238ae",
    600: "#1238ae",
    500: "#274ac4",
    400: "#4e66cd",
    300: "#7081d6",
    200: "#9aa5e2",
    100: "#c3c8ed",
     50: "#e7e9f8"
};
primaryColor['main'] = primaryColor[800];

const secondaryColor = {
    900: "#3c3c3c",
    800: "#606060",
    700: "#818181",
    600: "#979797",
    500: "#c2c2c2",
    400: "#dedede",
    300: "#f0f0f0",
    200: "#f5f5f5",
    100: "#fafafa",
     50: "#FFFFFF"
};
secondaryColor['main'] = secondaryColor[50];

我不确定export在这里如何。

index.js中,我想同时importprimaryColor secondaryColor

导出和导入它们的正确/可能方法是什么? 我以为我知道如何导出和导入,但是由于出现错误,我不确定自己做错了什么。

3 个答案:

答案 0 :(得分:1)

export const primaryColor = {
    900: "#001a8f",
    800: "#002EA2",
    700: "#1238ae",
    600: "#1238ae",
    500: "#274ac4",
    400: "#4e66cd",
    300: "#7081d6",
    200: "#9aa5e2",
    100: "#c3c8ed",
     50: "#e7e9f8"
};
primaryColor['main'] = primaryColor[800];

export const secondaryColor = {
    900: "#3c3c3c",
    800: "#606060",
    700: "#818181",
    600: "#979797",
    500: "#c2c2c2",
    400: "#dedede",
    300: "#f0f0f0",
    200: "#f5f5f5",
    100: "#fafafa",
     50: "#FFFFFF"
};
secondaryColor['main'] = secondaryColor[50];

并按如下所示导入

import { primaryColor, seondaryColor } from './style/colors.js'

答案 1 :(得分:0)

您可以从colors.js文件中导出

export default { primaryColor, seondaryColor };

像这样从index.js文件中导入它:

import { primaryColor, seondaryColor } from './style/colors.js'

您可以在此处了解有关命名和默认导入/导出的更多信息:imports exports

答案 2 :(得分:0)

在您的colors.js文件中,执行以下操作

const primaryColor = {
    900: "#001a8f",
    800: "#002EA2",
    700: "#1238ae",
    600: "#1238ae",
    500: "#274ac4",
    400: "#4e66cd",
    300: "#7081d6",
    200: "#9aa5e2",
    100: "#c3c8ed",
    50: "#e7e9f8"
};
primaryColor['main'] = primaryColor[800];

const secondaryColor = {
    900: "#3c3c3c",
    800: "#606060",
    700: "#818181",
    600: "#979797",
    500: "#c2c2c2",
    400: "#dedede",
    300: "#f0f0f0",
    200: "#f5f5f5",
    100: "#fafafa",
    50: "#FFFFFF"
};
secondaryColor['main'] = secondaryColor[50];

export { primaryColor, secondaryColor };

在您的index.js中,将其像这样使用:

import { primaryColor, secondaryColor } from './style/colors.js';
...
primaryColorMain = primaryColor['main'];
secondaryColorMain = secondaryColor['main'];

希望这会有所帮助!