2017-06-14 100 views
1

我想構建一個反應組件庫作爲節點模塊,然後將其導入到不同的項目中。但是,如果我嘗試導入組件,它只會返回一個空對象。Webpack輸出爲空對象

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中的package.json

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') 
      ] 
     } 
    ] 
    } 
} 

主要屬性是bundle.js

我想通了我在一個項目中導入Button,它只是一個空對象。在我看來,好像webpack不會正確捆綁索引文件。任何想法在這裏可能是錯的?

回答

2

默認情況下,webpack包不會公開您的導出,因爲它假定您正在構建應用程序而不是庫(這是webpack的更常用的用途)。您可以通過配置output.libraryoutput.libraryTarget來創建庫。

output: { 
    path: __dirname, 
    filename: 'bundle.js', 
    library: 'yourLibName', 
    libraryTarget: 'commonjs2' 
}, 

output.libraryTarget是模塊,這也將讓你露出庫作爲一個全局變量的格式。 commonjs2是Node使用的模塊格式。有關commonjscommonjs2之間的差異,請參閱What is commonjs2?

由於您使用的是React,因此您會希望庫的使用者將React作爲依賴項存在,因此您不希望將其包含在您的包中。要做到這一點,您可以將其定義爲External。這顯示在Authoring Libraries中,它會引導您通過一個小例子。

+0

非常感謝!現在它正在工作。 :) – SeBe