gpt4 book ai didi

reactjs - 导入自定义 npm 包会导致空/空对象

转载 作者:行者123 更新时间:2023-12-03 13:56:38 30 4
gpt4 key购买 nike

我可以在同一包中导入 MyComponent 并将其呈现在页面上,但无法链接或下载 MyComponent 包并导入该组件。

package.json:

{
"name": "my-component",
"version": "1.0.0",
"main": "dist/index.js",
"directories": {},
"dependencies": {},
"devDependencies": {
"babel-loader": "^6.2.3",
"babel-preset-es2015": "",
"babel-preset-react": "",
"css": "^2.2.1",
"css-loader": "^0.23.1",
"file-loader": "^0.8.5",
"node-sass": "^3.4.2",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"sass": "^0.5.0",
"sass-loader": "^3.1.2",
"style": "0.0.3",
"style-loader": "^0.13.0",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}

webpack.config.js:

var path = require('path');

module.exports = {
entry: './src/MyComponent.jsx',
output: {
path: './dist/',
filename: './index.js'
},
module: {
loaders: [{
test: /\.jsx$/,
include: path.resolve(__dirname),
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.scss$/,
include: /.scss$/,
loader: 'style!css!sass'
},
{
test: /\.html$/,
loader: "file?name=[name].[ext]",
},]
}
};

./src/MyComponent.jsx

import React from 'react';

export default class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>Hello World.</div>
);
}
}

MyComponent.propTypes = {
class: React.PropTypes.string
}
MyComponent.defaultProps = {
class: ''
}

console.log(MyComponent)

使用 webpack 开发服务器,我可以将此组件导入到另一个文件中并将其渲染到页面。

当我在另一个项目中链接和/或安装 webpack 构建的结果时,我希望能够执行相同的操作,如下所示:

new-app.jsx:

import React from 'react'
import ReactDOM from 'react-dom'
import MyComponent from 'my-component'
console.log(MyComponent)
ReactDOM.render(MyComponent, document.body)

当我从“my-component”导入模块时,MyComponent.jsx 中存在的 console.log 语句按预期记录“function MyComponent(props) {...”,但新的 console.log 语句应用程序记录一个空对象。

渲染 new-app.jsx 时的控制台输出:我相信第一个日志是来自 MyComponent.jsx 的日志,第二个日志来 self 的新应用程序。

index.js:19783 MyComponent(props) {
_classCallCheck(this, MyComponent);

return _possibleConstructorReturn(this, Object.getPrototypeOf(MyComponent).call(this, props));
}
index.js:58 Object {}

我的配置中是否缺少任何内容?我是否以错误的方式导出/导入?

最佳答案

解决方案是将其添加到 webpack.config.js 的输出中

library: 'MyComponent',
libraryTarget: 'umd'

关于reactjs - 导入自定义 npm 包会导致空/空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875467/

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