reactjs - 准备一个 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 配置,因为它应该可以正常工作,就像我目前使用的许多其他包一样。
解决方案
我解决了它,感谢@zerkms 为我的研究所需的第一步。
脚步:
- 安装 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' } }
- 在主文件夹中创建了一个.babelrc ,内容如下:
{ "presets": [ "react", "env", "stage-0" ] }
- 创建了一个.npmignore文件:
src .babelrc webpack.config.js
- 使用以下内容创建了一个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" } }
- npm 安装
- npm 运行构建
- npm 版本 1.0.0(更新增量)
- npm 发布
完毕!
这些文章很有帮助:
推荐阅读
- javascript - 从功能文件导航到步骤定义:任何插件
- r - 为分组条形图重新排序图例和条形图
- android - 如何在设定的时间在firebase中写入?
- javascript - Webpack:编译文件夹但保留单独的文件?
- rust - 如何修复在此范围内找不到派生宏“反序列化”?
- caching - 如何使用 Guava 缓存并行化 Flink 作业?
- batch-file - How to limit depth of DIR /S?
- php - 更改 wordpress {{meta:field}} 值
- prolog - How to describe commutative rules in prolog?
- r - 在数据框中使用 R mutate 在表中生成自引用键