首页 > 解决方案 > 当 npm start 时,react 组件模块未在其自己的目录中呈现

问题描述

TLDR:npm start 不是渲染组件

因此,在开发可分发的反应组件时,我对文件夹结构有点困惑。

我希望能够在模块目录本身中演示我的模块,并能够在另一个应用程序中分发该组件。

这是我当前的目录

在此处输入图像描述

目前 npm start 给了我这个

在此处输入图像描述

这是我的 webpack 配置

var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './'),
    filename: 'index.js',
    libraryTarget: 'commonjs2' // u sorta need this

  },
  module: {
    rules: [
      {
        test: /\.js$/,

        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: { 
            presets: ['@babel/preset-env', '@babel/react'],
            plugins:['@babel/plugin-proposal-class-properties']
          }
        }
      }
    ]
  },
//  public directory will render the component.
  devServer: {
    contentBase: __dirname  + './dist',
    compress: true,
    port: 9000,
    watchContentBase: true,
    progress: true
  },

};

dist/index.js

import React from "react";
import ReactDOM from "react-dom";
import Fetch from '../src';

const App = () => (
    <div>
        <Fetch/>
    </div>
)

ReactDOM.render(<App />, document.getElementById("root"));

索引.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello React</title>
  </head>
  <body>
    <div id="root"></div>

 </body>
</html>

src/index.js

import Fetch from './Fetch';

export default Fetch;

标签: reactjswebpack

解决方案


使用故事书进行演示并记录您的可重用组件。更好的方法是通过将 .stories.js 文件添加到每个组件来在组件级别创建故事。

结帐:https ://storybook.js.org/ 。

对于文件夹结构,您可以从 create-react-app 开始,它为您提供构建、运行和测试所需的所有功能。

结帐:https ://github.com/facebook/create-react-app


推荐阅读