【问题标题】:NPM Self Published Component cannot be found when using it in a React Project在 React 项目中使用时找不到 NPM 自发布组件
【发布时间】:2018-11-28 20:24:16
【问题描述】:

我创建了自己的 React 组件并将其发布以供使用。 我刚刚完成了通过 webpack 进行分发和路由的缩小。 (Babel 过去只是将所有文件转译并复制到 dist)。

但是我现在似乎无法再为我的项目导入它了。

我安装如下: npm i react-subreddit-posts

然后像这样导入:

import SubredditPosts from 'react-subreddit-posts';

然后得到这个错误:

Module not found: Can't resolve 'react-subreddit-posts'

所以我一定是错误地导出了模块或错误地缩小了它???

这里是源代码:

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>
      );
    }
}

这是通过 npm 安装后 node_modules 中的内容:

我可以从 src 中很好地导出它,但不能在它发布和分发时!

包.json:

{
  "name": "react-subreddit-posts",
  "version": "1.0.12",
  "description": "React component for displaying subreddit posts in different styles",
  "main": "dist/main.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/stcalica/react-subreddit-posts"
  },
  "directories": {
    "example": "example"
  },
  "scripts": {
    "test": "jest",
    "start": "webpack-dev-server --mode development",
    "transpile": "rm -rf dist && webpack",
    "prepublishOnly": "npm run transpile",
    "compile": "webpack --config ./webpack.config.js --progress"
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./test/setupTest.js"
  },
  "keywords": [
    "react",
    "reddit"
  ],
  "author": "Kyle Calica",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-jest": "^23.0.1",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.11",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^23.1.0",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-test-renderer": "^16.4.1",
    "style-loader": "^0.21.0",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "webpack": "^4.12.0",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {}
}

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const htmlWebpackPlugin = new HtmlWebpackPlugin({
//   template: path.join(__dirname, 'example/src/index.html'),
//   filename: './index.html'
// });

module.exports = {
  entry: path.join(__dirname, 'example/src/index.js'),
  output: {
    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']
      }
    ]
  },
  // plugins: [ htmlWebpackPlugin ],
  resolve: {
    extensions: ['.js', '.jsx']
  },
  devServer: {
    port: 3001
  }
};

【问题讨论】:

    标签: reactjs webpack npm-install package.json


    【解决方案1】:

    在您的 github 中,我看到您的 .gitignore 文件中有 dist 路径,但是如果您看到 package.json,您会看到您的 repo 指向的 dist/index.js 文件不存在,因为您添加了它到.gitignore。

    试试:

    • 删除 gitignore 中的排除项
    • 重新编译您的应用并创建 dist 文件夹
    • 在 npm 中再次发布
    • 通过 npm/yarn install 重新下载你的依赖项
    • 并确保您获得了最新版本的依赖项

    【讨论】:

    • 我认为 .gitignore 和 .npmignore 会被区别对待。正如您在我刚刚发布的更新中的图片中看到的那样,它肯定存在。但是当我的 webpack 输出 main.js 时,你的权利我有 dist/index.js。我将手动编辑 node_module 安装,看看是否能解决我的问题。
    • 现在我在缩小错误后收到此错误:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 有什么想法吗?我在想我可能还是出口错了?
    • 是不是因为我把它缩小了,它现在看不到SubredditPosts
    • 是的,这是因为您编译库的方式是编译为 IEFF,但 webpack 实际上需要以下模块格式之一的库:CommonJs、A​​MD、ES6 模块。我会尝试立即使用 webpack 编译代码,而不仅仅是使用以下配置的 babel: output.libraryTarget = 'commonjs2';
    • 还有配置externals,看看我很久以前写的一个配置github.com/miguelcrespo/react-progressive-loading/blob/master/…
    猜你喜欢
    • 2022-01-18
    • 2017-09-11
    • 2021-06-29
    • 2018-03-30
    • 2021-01-04
    • 1970-01-01
    • 2016-06-10
    • 2021-08-10
    • 2021-02-10
    相关资源
    最近更新 更多