首页 > 解决方案 > 准备一个 React 组件以在 npm 上发布

问题描述

我有一个想要在 npm 中发布的组件,我只是通过从项目的 components 文件夹中导入它来测试它。

我设法发布它,但现在我得到:

./node_modules/@ / /index.js 中的错误模块解析失败:意外令牌 (11:8) 您可能需要适当的加载程序来处理此文件类型。

我的 index.js 如下:

import React from "react"
import Main from "./bootstrap/containers/main"

export default class BootstrapTable extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
        <Main {...this.props} changePage={(p) => this.props.changePage(p)}/>
    )
  }
}

旁注:我不需要更改 webpack 配置,因为它应该可以正常工作,就像我目前使用的许多其他包一样。

标签: reactjsnpm

解决方案


我解决了它,感谢@zerkms 为我的研究所需的第一步。

脚步:

  1. 安装 webpack 并将以下配置添加到webpack.config.js(我的 index.js 在 ./src 中,并且外部非常重要,因此您不会加载 react 实例):
var path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [{
      test: /\.js?$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader'
      }
    }]
  },
  externals: {
    'react': 'react',
    'react-dom': 'react-dom',
    'react-bootstrap': 'react-bootstrap'
  }
}
  1. 在主文件夹中创建了一个.babelrc ,内容如下:
{
    "presets": [
        "react",
        "env",
        "stage-0"
    ]
}
  1. 创建了一个.npmignore文件:
src
.babelrc
webpack.config.js
  1. 使用以下内容创建了一个package.json文件(您的包可能不同,但基本上只需安装您需要的“npm i package-name”):
{
  "name": "@scope/package-name",
  "version": "1.0.0",
  "description": "My component",
  "main": "dist/index.js",
  "scripts": {
    "build": "webpack"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/myrepo.git"
  },
  "keywords": [
    "react",
    "bootstrap"
  ],
  "author": "Me",
  "license": "MIT",
  "peerDependencies": {
    "react": "^16.4.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.4.0"
  },
  "devDependencies": {
    "react": "^16.4.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.4.0",
    "babel-core": "^6.21.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.24.1",
    "path": "^0.12.7",
    "webpack": "^4.5.0",
    "webpack-cli": "^2.0.14"
  }
}
  1. npm 安装
  2. npm 运行构建
  3. npm 版本 1.0.0(更新增量)
  4. npm 发布

完毕!

这些文章很有帮助:


推荐阅读