简体   繁体   English

找不到发布的React组件模块

[英]can't find published React component module

I published a React component to NPM and when trying to use it in another project I am not able to find the module! 我向NPM发布了一个React组件,当试图在另一个项目中使用它时,我找不到该模块!

Module not found: Can't resolve 'react-subreddit-posts' in '/Users/kyle.calica/Code/exmaple/app/src'

I was having trouble with creating a Webpack bundle which I could import from when developing. 我在创建Webpack包时遇到了麻烦,该包可以在开发时从中导入。 I believe it is because I am making ES6 class notations but trying to compile so that I can import? 我相信这是因为我正在制作ES6类符号,但是试图进行编译以便可以导入? I was able to "fix" it. 我能够“修复”它。 But now I'm having trouble using it. 但是现在我在使用它时遇到了麻烦。

Here is my React component's webpack.prod.config.js 这是我的React组件的webpack.prod.config.js

const path = require("path");

module.exports = {
  mode: 'production',
  entry: path.join(__dirname, "src/index.js"),
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: "commonjs2"
    },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["react"],
              plugins: ["transform-class-properties"]
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },
  resolve: {
    extensions: [".js", ".jsx"]
  }
};

Here is my entry JS file for the component, index.js a good example of how I'm making the classes in my React component: 这是我的组件入口JS文件index.js ,这是我如何在React组件中制作类的一个很好的例子:

import React, { Component } from 'react';
import ListContainer from './ListContainer';
import ListItemComponent from './ListItemComponent';

const redditAPI = 'https://www.reddit.com/r/';

export default class SubredditPosts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redditPosts: [],
      isLoading: true
    };
  }

  componentDidMount() {
    const uri = `${redditAPI}${this.props.subreddit}.json`;
    fetch(uri)
      .then(data => data.json())
      .then(this.handlePosts)
      .catch(err => console.error(err));
  }

  handlePosts = (posts) => {
    const apiPosts = posts.data.children.map((post, index) => {
      return {
        key: index,
        title: post.data.title,
        media: this.getMediaFromPost(post),
        link: post.data.url
      };
    });

    this.setState({
      redditPosts: apiPosts,
      isLoading: false
     });
  }

  getMediaFromPost = (post) => {
    const extension = post.data.url.split('.').pop();

    if (post.data.hasOwnProperty('preview') &&  !extension.includes('gif')) {
      return post.data.preview.images[0].source.url;
    }

    //do not use includes! because of Imgur's gifv links are not embeddable
    if (extension === 'gif' || extension.includes('jpg') ||  extension.includes('jpeg')) {
      return post.data.url;
    }

    //if can't load media then place placeholder
    return this.props.placeholder;
  }

    render() {
      return(
        <ListContainer display={this.props.display}>
        { !this.state.isLoading && this.state.redditPosts.map(post => (
          <ListItemComponent
            display={this.props.display}
            key={post.key}
            link={post.link}
            media={post.media}
            title={post.title}
            height={this.props.height}
            width={this.props.width}
          />
        ))}
        </ListContainer>
      );
    }
}

And here is the App.js in my project trying to consume the published React component that I pulled from NPM: 这是我项目中的App.js ,试图使用从NPM中提取的已发布的React组件:

import React, { Component } from 'react';
import SubredditPosts  from 'react-subreddit-posts';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
        <div class="row">
        <SubredditPosts
          subreddit="aww"
          display="tile"
          placeholder="some_link_image_url_OR_image_path"
          width="250px"
          height="250px"
          />
        </div>
      </div>
    );
  }
}

export default App;

What am I doing wrong with my bundling and exporting of the React component? 我捆绑和导出React组件时出了什么问题? Or am I just importing it wrong? 还是我导入错误?

Just installed your package and it turns out to be a bad publish. 刚安装了您的软件包,结果发现它是一个不好的发布。

When you import a package from node_modules, node/webpack finds the directory, reads a package.json file in it, then imports the file indicated by the main field in package.json. 从node_modules导入软件包时,node / webpack会找到目录,读取其中的package.json文件,然后导入package.json中main字段指示的文件。 If any of those steps fail your import will fail to resolve. 如果其中任何一个步骤失败,则导入将无法解决。

Your package.json says "main": "dist/index.js" but there's no dist directory in the release, only a lib directory. 您的package.json表示"main": "dist/index.js"但发行版中没有dist目录,只有lib目录。

Changing the field to "main": "lib/index.js" would probably work, but there's other issues as well. 将字段更改为"main": "lib/index.js"可能会起作用,但是还有其他问题。 Your dependencies are all over the place. 您的依赖关系无处不在。 devDependencies are packages need only by developers working on the package. devDependencies是仅由开发人员使用的软件包所需的软件包。 It's used for build tools, testing tools, linters, etc. dependencies are need for the package to work correctly. 它用于构建工具,测试工具,短毛绒等。为了使程序包正常工作,需要dependencies The difference is that dependnecies of a dependency will be installed when you install a package, but devDependencies of a dependency won't be installed. 不同的是, dependnecies的依赖会当您安装包进行安装,但devDependencies依赖的将不会安装。

In your case, you need react and react-dom in dependencies and everything else in devDependnecies . 在您的情况下,您需要在dependenciesdevDependnecies其他所有内容上进行react和react-dom。 Also npm is always installed globally and you don't need it in your package.json at all. 同样,npm始终安装在全局范围内,而您在package.json中根本不需要它。

I'd recommend you look up a guide for maintaining an open source package and/or check how an existing one is set up. 我建议您查阅一份指南,以维护开源软件包和/或检查如何设置现有软件包。 It's not too hard to understand but there's a lot of things you should know that you just don't care about when developing an app. 理解起来并不难,但是您应该知道很多事情,您在开发应用程序时并不关心。

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

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