我想發佈一個基本的React組件到我的npm註冊表並試圖重用它。我想我沒有按照正確的方式來分發我的反應成分。下面是我有:發佈一個反應組件到npm並重用它
這是目錄結構:
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']
}
}
]
},
};
我導入模塊中使用import MyComponent from '@pankaj/my-component'
另一個項目。
當我使用像
我收到以下錯誤此組件:
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')
);
我有了 '根' 的div一個index.html。
試着做'的console.log(MyComponent的)'導入它來檢查什麼是真正得到導入後。您可能無法真正導入它並試圖在未定義的''上調用'createElement'。 –
@PedroCastilho組件是:[object object]'。有沒有辦法看到MyComponent? – Pankaj
你的問題是你的渲染函數沒有返回語句,所以當你嘗試渲染時會得到'undefined'。 –