gpt4 book ai didi

reactjs - 如何将 Reactjs 组件发布到 npm

转载 作者:行者123 更新时间:2023-12-03 13:50:35 26 4
gpt4 key购买 nike

目标:我有一个简单的 React 组件,有两个导入:reactprop-types,我正在尝试将其发布到npm。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class MyComponent extends Component {
...
}

export default MyComponent;

问题:我以前从未发布过任何内容,因此我不确定如何设置所有内容。以下是我的尝试 - 当我尝试使用 npm link 测试它时,我可以成功导入该组件,但一旦我尝试使用它,它就会出现以下错误:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

文件结构:

├── node_modules/
├── lib/
| ── index.js <--- this is where webpack builds to
├── src/
| ── index.js <--- this is the react component
|
├── package.json
├── webpack.config.js
├── .babelrc
├── .npmignore
├── .gitignore

Package.json:

{
"name": "...",
"version": "1.0.0",
"description": "...",
"main": "lib/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
"repository": {
"type": "git",
"url": "..."
},
"author": "...",
"license": "MIT",
"bugs": {
"url": "..."
},
"homepage": "...",
"dependencies": {
"prop-types": "^15.0.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"webpack": "^3.10.0",
},
"peerDependencies": {
"react": "^15.0.0 || ^16.0.0",
"react-dom": "^15.0.0 || ^16.0.0"
}
}

webpack 文件:

const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'lib'),
filename: 'index.js'
},
module: {
rules: [
{
test: /\.(js)$/,
use: 'babel-loader'
}
]
},
externals: {
'react': 'commonjs react',
'react-dom' : 'commonjs react-dom'
}
};

.babelrc:

{
"presets": ["env", "react"],
"plugins": ["transform-class-properties", "transform-object-rest-spread"]
}

导入:

并且,为了澄清,我没有混淆默认导入和命名导入,该包将作为默认导入导入:

import MyComponent from 'my-component';

最佳答案

webpack 配置选项 output.libraryTarget 可用于告诉 webpack 它应该创建的构建类型:

  • "commonjs2":入口点的返回值将分配给 module.exports
  • “umd”:生成可与 CommonJS、AMD 和老式脚本标签/全局变量配合使用的构建(归功于 @JoeClay )

请参阅此处的文档:https://webpack.js.org/configuration/output/#module-definition-systems

这些设置会将您的组件导出为 CommonJS 模块,您可以根据需要导入该模块。

关于reactjs - 如何将 Reactjs 组件发布到 npm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48191496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com