准备React组件以在npm上发布

时间:2018-06-06 01:15:04

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

1 个答案:

答案 0 :(得分:2)

我解决了这个问题,感谢@zerkms我研究所需的第一步。

<强>步骤:

  1. 已安装webpack并将以下配置添加到 webpack.config.js (我的index.js位于./src中,外部非常重要,因此您不会加载反应实例):< / LI>
    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
    2. {
          "presets": [
              "react",
              "env",
              "stage-0"
          ]
      }
      
      1. 使用以下内容创建 .npmignore 文件
      2. src
        .babelrc
        webpack.config.js
        
        1. 使用以下内容创建 package.json 文件(您的软件包可能不同,但基本上只需安装您需要的软件“npm i package-name”):
        2. {
            "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 install
          2. npm run build
          3. npm版本1.0.0(更新增量)
          4. npm publish
          5. 完成!

            这些文章很有帮助:

相关问题