3

When I run webpack, _ returns as undefined on window: window._ ::: Error: _ is not defined. I thought that putting _ inside the plugins will expose it to window. Is my understanding incorrect?

const webpack = require('webpack');

const plugins = new webpack.ProvidePlugin({
    $: "jquery",
    _: "underscore"
});

module.exports = {
    entry: {
        app: './src/main/app/components/main.module.js',
        vendor: [
            'jquery',
            'underscore'
        ]
    },
    output: {
        filename: './src/main/resources/dist/app/scripts/[name].bundle.js',
    },
    plugins: [plugins],
    devtool: 'inline-source-map'
};
Jon
  • 8,205
  • 25
  • 87
  • 146

3 Answers3

1

You're trying to add it as a global variable? Try adding this to your .ts / .js file:

window['_'] = require('underscore');

Faisal
  • 139
  • 7
1

providePlugin is used to make libraries available in the context of other modules in the webpack bundle. For example, this usage of providePlugin:

const plugins = new webpack.ProvidePlugin({
  $: "jquery",
  _: "underscore"
});

will allow access to jquery lib in ./src/main/app/components/main.module.js via the $ variable.

If you want to expose jquery to the window as window.$, you can either use webpack's expose-loader, or simply update the window in your entry file (main.module.js):

window.$ = $; //$ is defined via providePlugin
window._ = _; //_ is defined via providePlugin
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
1

Did you load the underscore.js in your index file?

<script src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js'></script>

Voro
  • 235
  • 1
  • 12