Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: [
    'underscore',
  ],
  plugins: [
    new ExtractTextPlugin('si-styles.css'),
    new webpack.ProvidePlugin({
      underscore: 'underscore',
    }),
  ],
  postcss: function(webpack) {
    return [
      postcssImport({ addDependencyTo: webpack }), // Must be first item in list
      precss,
      autoprefixer({ browsers: ['last 2 versions'] }),
    ];
  },

};
like image 514
matt-p Avatar asked Jun 23 '16 14:06

matt-p


1 Answers

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:

entry: {
    main: [
        './app/js/main.js'
    ],
    vendor: [
            'underscore',
            'lodash',
            'my-awesome-library!'
        ]
  }

UPDATE: There is a very good tutorial in how to use webpack in production on egghead.io.. Try to check it out!

like image 86
piratz Avatar answered Sep 27 '22 18:09

piratz