[英]ES6/React package - exported classes undefined when trying to import (built with webpack)?
我們創建了一個包來收集在多個項目之間共享的React組件,但是由於某些原因,當我們嘗試導入包時,導出是不確定的。 為了這個問題,我提供了一個調整后的index.js
來說明問題(在實際情況下,類位於單獨的文件中):
import React, {Component} from 'react';
class MyComponent1 extends Component {
render () {
return (<div>Component 1</div>);
}
}
class MyComponent2 extends Component {
render () {
return (<div>Component 2</div>);
}
}
console.log('###### MyComponent1', MyComponent1);
console.log('###### MyComponent2', MyComponent2);
export { MyComponent1, MyComponent2 };
export default function () {
console.log('Monkey madness');
}
// Shows expected exports in module.exports, but
// aren't there on import
console.log('###### Module', module);
我們正在使用的webpack.conf.js
:
const webpack = require('webpack');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
var BUILD_DIR = path.resolve(__dirname, 'lib');
var APP_DIR = path.resolve(__dirname, 'src');
module.exports = {
entry: APP_DIR + '/index.js',
devtool: 'source-map',
output: {
//library: 'myReactComponents',
path: BUILD_DIR,
filename: 'index.js'
},
module: {
rules: [{
test: /\.js$/,
// include: APP_DIR,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'react'],
}
}
}]
},
plugins: [
new CleanWebpackPlugin([BUILD_DIR], {
root: path.resolve(__dirname),
verbose: true,
dry: false,
exclude: []
})
]
};
運行webpack
生成兩個文件lib/index.js
和lib/index.js.map
:
Hash: 3a52a7d7bb440ee0c467
Version: webpack 3.2.0
Time: 2331ms
Asset Size Chunks Chunk Names
index.js 158 kB 0 [emitted] main
index.js.map 186 kB 0 [emitted] main
[18] ./src/index.js 3.33 kB {0} [built]
+ 36 hidden modules
在下游項目中,我們的組件包已安裝npm,然后在代碼中具有:
import MyComponents, {MyComponent1, MyComponent2} from 'my-components';
console.log('>>> MyComponents', MyComponents);
console.log('>>> MyComponent1', MyComponent1);
console.log('>>> MyComponent2', MyComponent2);
運行此命令,我在程序包中看到控制台語句顯示:
>>> MyComponents {}
>>> MyComponent1 undefined
>>> MyComponent2 undefined
我試過調試,然后看到modules.exports確實采用了分配的值,但是很快就迷失了代碼中發生的所有其他事情。
誰能建議可能出什么問題以及如何解決這個問題?
順便說一句,我剛剛嘗試用gulp構建它,但沒有遇到這個問題,所以我懷疑我的webpack設置有問題嗎? 關鍵版本:
默認的libraryTarget
為var
。 文檔嘗試改為指定umd
。
還要檢查庫package.json
文件中的main
字段,以指向lib/index.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.