I have found a few StackOverflow questions related to this but none that match nor fix my problem.
I am writing a library in ES6 that is intended to be used in the browser and on the server. I have found a few HTTP request libraries that can be use on the server or browser (popsicle, axios). I have successfully used these libraries in both places but am having some issues when importing them in my source and using the outputted webpacked file.
My ES6 source file where I am importing the axios
library is
import axios from 'axios';
export default {
go: function() {
return axios.get('http://www.google.com');
}
};
My webpack config is
var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var WebpackNotifierPlugin = require('webpack-notifier');
var path = require('path');
var env = require('yargs').argv.mode;
var libraryName = 'library';
var source = '/src/test.js';
var plugins = [],
outputFile;
if (env === 'build') {
plugins.push(new UglifyJsPlugin({
minimize: true
}));
outputFile = libraryName + '.min.js';
} else {
outputFile = libraryName + '.js';
plugins.push(new WebpackNotifierPlugin())
}
var config = {
entry: __dirname + source,
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
externals: {},
module: {
loaders: [{
test: /(\.jsx|\.js)$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
}, {
test: /(\.jsx|\.js)$/,
loader: "eslint-loader",
exclude: /node_modules/
}]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
plugins: plugins
};
module.exports = config;
As you can see I am setting the libraryTarget to umd
and umdNamedDefine to true
And my .bablerc
is
{
"presets": ["es2015"],
"plugins": ["add-module-exports", "babel-plugin-add-module-exports"]
}
I am able use my library in the browser by including it in a script
tag but I am not able to use it when importing with node. I get an XMLHttpRequest is not defined
. The axios library says it uses XMLHttpRequest when on the browser and http when running in node but for some reason it is not detecting it is being run on the server. I am having this issues with a few UML libraries so believe it is not the specific package. Also, since I can use these libraries in node ES5 without running webpack or babel I am led to assume it is a configuration issue with webpack.
How can I import these UMD style libraries in ES6 and generate a library with Webpack and Babel that can be used on the server and browser?