【发布时间】:2018-06-19 20:43:57
【问题描述】:
目标:我有一个简单的 React 组件,其中包含两个导入:react 和 prop-types,我正在尝试将其发布到 npm。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component {
...
}
export default MyComponent;
问题:我以前从未发布过任何东西,所以我不确定如何设置所有内容。以下是我尝试过的 - 当我尝试使用 npm link 对其进行测试时,我可以成功导入组件,但是一旦我尝试使用它,它就会给我以下错误:
元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:对象。你 可能忘记从定义它的文件中导出您的组件, 或者您可能混淆了默认导入和命名导入。
文件结构:
├── 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';
【问题讨论】:
-
你能展示你如何在客户端代码中导入组件吗?确保您像这样导入它:
import MyComponent from 'mycomponent'而不是像这样:import { MyComponent } from 'mycomponent',因为您在模块中使用了export default。 -
我将其作为默认导入导入
标签: reactjs npm webpack package.json