我试图将一个基本的React组件发布到我的npm注册表并尝试重用它.我想我没有按照正确的方式分发我的反应组件.这就是我所拥有的: 这是目录结构: MyReactPOC - main.jsx - .npmrc - package.json
这是目录结构:
MyReactPOC
-> main.jsx
-> .npmrc
-> package.json
-> webpack.config.js
main.jsx
import React from 'react';
class MyComponent extends React.Component {
render() {
return (
<div>
<p>Hello from MyComponent!!</p>
</div>
);
}
}
export default MyComponent
的package.json
{
"name": "@pankaj/my-component",
"version": "1.0.7",
"description": "POC for importing a component",
"main": "./dist/bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prepublish": "webpack --config webpack.config.js"
},
"repository": {
"type": "git",
"url": "my git repo"
},
"author": "Pankaj",
"license": "ISC",
"dependencies": {
"react": "~15.5.4",
"react-dom": "~15.5.4"
},
"devDependencies": {
"babel-cli": "~6.24.1",
"babel-core": "~6.24.1",
"babel-loader": "~6.4.1",
"babel-preset-es2015": "~6.24.1",
"babel-preset-react": "~6.24.1",
"webpack": "~2.4.1"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './main.jsx',
output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' },
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
我使用’@pankaj / my-component’中的import MyComponent在另一个项目中导入模块.
当我使用这个组件时
我收到以下错误:
React.createElement: 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.
请帮助我了解分发反应组件的正确方法,以便我们组织内的其他项目可以使用它们.
以下是我使用此组件的方法:
ComponentUse.js
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from '@pankaj/my-component';
ReactDOM.render(
<MyComponent/>,
document.getElementById('root')
);
我有一个index.html,它有’root’div.
每个反应组件都需要一个return语句.在渲染函数中添加一个return语句,它应该可以工作....
render() {
return (<div>...</div>)
}
您不能直接从您的反应组件渲染到Dom,而是返回它以便反应可以使用它.
在webpack中,使用output.library https://webpack.js.org/concepts/output/#output-library将输出文件指定为库
