Reputation: 7554
We have created a package for collecting together React components we share between several projects, but for some reason when we try to import the package the export are undefined. For purposes of the question I am providing an adjusted index.js
that illustrates the issue (in the real scenario the classes are in separate files):
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);
The webpack.conf.js
we are using:
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: []
})
]
};
Running webpack
generates two files lib/index.js
and 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
In the downstream project our components package is npm installed and then in the code we have:
import MyComponents, {MyComponent1, MyComponent2} from 'my-components';
console.log('>>> MyComponents', MyComponents);
console.log('>>> MyComponent1', MyComponent1);
console.log('>>> MyComponent2', MyComponent2);
Running this I see the console statements in our packages shows:
>>> MyComponents {}
>>> MyComponent1 undefined
>>> MyComponent2 undefined
I have tried debugging this and see the modules.exports does take the assigned values, but then quickly get lost with everything else happening in the code.
Can anyone suggest what might be going wrong and how to try to solve this?
BTW I just tried building this with gulp and I don't run into this issue, so I am suspecting something is wrong with my webpack setup? Key versions:
Upvotes: 1
Views: 967
Reputation: 45106
Default libraryTarget
is var
. Docs Try to specify umd
instead.
Also check main
field in your library package.json
file to point to lib/index.js
Upvotes: 1