【问题标题】:Preparing a React component to publish on npm准备一个 React 组件以在 npm 上发布
【发布时间】:2018-06-06 01:15:03
【问题描述】:

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

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

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

我的 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 配置,因为它应该可以正常工作,就像我目前使用的许多其他包一样。

【问题讨论】:

标签: reactjs npm


【解决方案1】:

我解决了这个问题,感谢@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 发布

完成!

这些文章很有帮助:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-09
    • 2019-08-18
    • 1970-01-01
    • 2017-09-11
    • 2017-03-08
    • 2018-09-03
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多