我想构建一个React组件库作为节点模块,然后将其导入到不同的项目中。但是,如果我尝试导入组件,它只会返回一个空对象。
button.jsx:
import React, {Component} from 'react' export class Button extends Component { render() { return <button className='btn'>Hello Button comp</button> } } export default Button
index.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.library
output.libraryTarget
output: { path: __dirname, filename: 'bundle.js', library: 'yourLibName', libraryTarget: 'commonjs2' },
output.libraryTarget是模块的格式,这也将允许您将库公开为全局变量。commonjs2是Node使用的模块格式。请参阅什么是commonjs2?commonjs和之间的区别commonjs2。
commonjs2
commonjs
由于您使用的是React,因此可以期望该库的使用者将React作为依赖项存在,因此您不希望将其包含在包中。为此,您可以将其定义为External。创作库中对此进行了显示,它为您提供了一个小例子。