繁体   English   中英

从React中的索引文件导入

[英]Importing from index files in react

我不能将索引文件用于组件库中的导入,而只能用于外部。 我正在使用以下目录结构:

+ components
  | index.js
  + atoms
    | index.js
    + label
      | label.jsx
      | label.css
  + hoc
    | index.js
    + withFrame
      | withFrame.jsx
      | withFrame.css
  + clientSpecificStyle
    | index.js
    | clientLabel.jsx

索引文件只是导出默认导入

// just one sample
export { default as Label } from './label/label;

我想要做的是能够区分组件的典型(基本)样式和客户特定的样式。 我的clientLabel只是一个带有边框的标签:

 import React, {Component} from 'react';

 // this doesn't work
 import Label from '../atoms/index';
 import withFrame from '../hoc/index';

 // this works
 import Label from '../atoms/label/label';
 import withFrame from '../hoc/withFrame/withFrame';

 @withFrame
 class ClientLabel extends Component {
   render() {
     return (
       <Label {...this.props}>{this.props.children}</Label>
     );
   }
 }

 export default ClientLabel;

当使用组件索引文件中的导入内容从“外部”(即,与组件位于同一文件夹层次结构中的演示页)一起使用时,它会按预期工作。 但是我无法从ClientLabel内的索引文件导入HoC和标签(失败时组件/功能未定义)。 但是,当直接使用HoC和Label组件文件进行导入时,它可以工作。 最顶层的索引文件(对于整个库)如下所示

export * from './atoms/index;
export * from './clientSpecificStyle/index';
//...

由于我希望这个项目能够成长为许多单独的组件,因此使用索引文件进行所有导入会更加方便,因此,我可以根据需要重新组织代码,并且只更改相应索引文件中的一行代码。

有可能使它工作吗?


我的webpack(v。3.6)配置可以正常工作-除此问题外-符合预期。 为了清楚起见,这是dev-config:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports =  {
  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    path.resolve('src', 'demo', 'demo.jsx')
  ],

  output: {
    path: path.resolve('dist'),
    filename: 'bundle.js',
  },

  resolve: {
    extensions: ['.js', '.jsx']
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'react-hot-loader/webpack!babel-loader',
        exclude: [/node_modules/]
      },
      {
        test: /\.css$/,
        loaders: [
            'style-loader?sourceMap',
            'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
        ]
      }
    ]
  },

  devServer: {
    contentBase: './dist',
    hot: true
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve('src', 'demo', 'index.html'),
      filename: 'index.html',
      inject: 'body'
    }),
    new webpack.NamedModulesPlugin()
  ]
};

因此,仅出于完整性考虑:正确的导入方法是

import {Label} from '../atoms

因为我已经完成了命名导出。

所有的荣誉都归@ReiDien

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM