我正在尝试创建一个带有一些React组件的npm包,我几乎用于所有项目 . 这是文件夹结构和文件内容:
-
/
-
dist /
-
bundle.js
-
src /
-
MyComponent.jsx
-
index.js
-
package.json
-
webpack.config.js
MyComponent.jsx
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<p>Hello, world!</p>
);
}
}
export default MyComponent;
index.js
// eventually there will be more components imported/exported here
import MyComponent from './MyComponent.jsx';
exports.MyComponent = MyComponent;
webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
path: './dist',
filename: 'bundle.js'
},
// some loaders...
};
package.json
{
"name": "my-library",
"files": [
"dist",
"src"
],
"main": "dist/bundle.js",
// the usual stuff...
}
这是我对这个过程的理解 . 首先,我用webpack构建src文件 . 这将查看/src/index.js,导入MyComponent类,然后将其导出,使其可用作MyComponent . 这都添加到/ dist中的bundle.js文件中 .
接下来,我用 npm pack
打包模块 . 这将创建一个包含/ src和/ dist目录的存档文件 .
然后我转到我的其他项目并运行 npm install ../path/to/archive/file
. 这会将模块添加到我的node_modules目录中 . 问题是,当我尝试导入和使用MyComponent时......
import React, { Component } from 'react';
import MyComponent from 'my-library';
class App extends Component {
render() {
console.log(<MyComponent />);
return (
<MyComponent />
);
}
}
export default App;
...并渲染该组件,我收到此警告和错误:
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `App`.
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `App`.
console.log的输出是一个React对象,但类型是 Object
,这似乎是警告所暗示的(我猜它应该是一个字符串) .
知道我错过了什么吗?
EDIT:
好吧,我离我更近了 . 我在我的webpack配置中添加了库选项:
output: {
library: 'my-library',
libraryTarget: 'umd'
}
...然后我能够使用这样的组件:
import MyLibrary from 'my-library';
const MyComponent = MyLibrary.MyComponent;
但我不想为每个组件都这样做 . 我的目标是:
import { MyComponent, MyOtherComponent } from 'my-library';
1 回答
您必须从组件index.js文件中导出组件,如下所示
然后在您的主项目中,使用导入它们