matt-p matt-p - 1 year ago 464
Javascript Question

Import Javascript library globally via Webpack

I am trying to remove script tags for javascript libraries from my html, and so have removed underscore.js from a template page.

To replace this, within my index.js (webpack entry point), I have the following

import 'underscore';

The size of the webpack outputted bundle.js file increases by 50k when I do this, so I know that the library is in bundle.js. However, underscore is not available when I try to use it in the console on a page which has the bundle.js included.

Any thoughts would be appreciated.

const webpack = require('webpack');
const path = require('path');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const postcssImport = require('postcss-import');

module.exports = {

context: __dirname + '/frontend',
devtool: 'source-map',
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, './static'),
module: {
loaders: [
{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['es2015'] } },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap&importLoaders=1!postcss') },
vendor: [
plugins: [
new ExtractTextPlugin('si-styles.css'),
new webpack.ProvidePlugin({
underscore: 'underscore',
postcss: function(webpack) {
return [
postcssImport({ addDependencyTo: webpack }), // Must be first item in list
autoprefixer({ browsers: ['last 2 versions'] }),


Answer Source

In order to achieve that you can use this webpack plugin:

new webpack.ProvidePlugin({
    underscore: "underscore"

by the way it is not necessary that you import the library in the index file of your directory. You will have access to the library also specifying a new entry point in your webpack config file.. You could then put all your vendor code in a vendor.js boundle like so:

vendor: [
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download