我想构建一个 React 组件库作为节点模块,然后将其导入到不同的项目中。但是,如果我尝试导入一个组件,它只会返回一个空对象。
按钮.jsx:
import React, {Component} from 'react'
export class Button extends Component {
render() {
return <button className='btn'>Hello Button comp</button>
}
}
export default Button
索引.js
var Button = require('./button/button').default;
module.exports = {
Button: Button
}
webpack.config.js
const Path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
},
entry: {
app: './src/components/index.js'
},
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: [
'es2015',
'react'
]
},
exclude: /node_modules/,
include: [
Path.resolve(__dirname, 'src')
]
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [
'es2015',
'react'
]
},
exclude: /node_modules/,
include: [
Path.resolve(__dirname, 'src')
]
}
]
}
}
package.json 中的主要属性是 bundle.js
我发现当我在项目中导入 Button 时,它只是一个空对象。在我看来,webpack 似乎没有正确捆绑索引文件。有什么想法这里可能有什么问题吗?
最佳答案
默认情况下,webpack 包不会公开您的导出,因为它假定您正在构建一个应用程序而不是一个库(这是 webpack 更常见的用法)。可以通过配置output.library
来创建库和 output.libraryTarget
.
output: {
path: __dirname,
filename: 'bundle.js',
library: 'yourLibName',
libraryTarget: 'commonjs2'
},
output.libraryTarget
是模块的格式,它还允许您将库公开为全局变量。 commonjs2
是 Node 使用的模块格式。参见 What is commonjs2? commonjs
和 commonjs2
的区别。
由于您使用的是 React,您会期望库的使用者将 React 作为依赖项存在,因此您不想将其包含在您的包中。为此,您可以将其定义为 External。 .这显示在 Authoring Libraries 中,它会引导您完成一个小示例。
关于javascript - Webpack 输出为空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44541561/