2

I have a web application who's (client side) javascript is written in es6 with the main entry point in app.js.

I can bundle it up using webpack, either referencing vendor libraries like jQuery externally, or including them in the bundle - depending on preference. In order for it to work correctly in the browser I have to specify libraryTarget and library like so:

//snip
entry: {
    "app.bundle": ["./app.js"],
},
output: {
    path: path.join(__dirname, "wwwroot\\js"),
    filename: "[name].js",
    libraryTarget: "var",
    library: "app"
}
//snip

However I'd like to have my vendor libraries bundled separately.

I can do this using CommonsChunkPlugin, but then it doesn't seem to play nicely with library* properties as they get applied to it as well. i.e I end up with app.jQuery instead of just jQuery

How can I separate out my vendor code and provide the appropriate globals to whatever needs them, while also exposing my application code to the browser correctly?

webpack.config here:

var path = require('path'),
    webpack = require('webpack');

module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        "app.bundle": ['./js/app.js'],
        "vendor.bundle": ['jquery', 'jquery-validation', 'jquery-validation-unobtrusive']
    },
    output: {
        path: path.join(__dirname, 'wwwroot\\js'),
        filename: '[name].js',
        libraryTarget: 'var',
        library: 'app'
    },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'stage-0']
                }
            }
        ]
    },
    resolve: {
        extensions: ['*', '.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor.bundle',
            minChunks: Infinity
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })
    ]
}
JamesT
  • 2,988
  • 23
  • 29

1 Answers1

0

If your jquery plugins are provided externally and you are developing a library, I'd suggest to use externals instead of ProvidePlugin. This means that you will have to provide jQuery explicitly when you will test your bundled library.

Externals

externals: {
  $: require.resolve('jquery'),
  'window.$': require.resolve('jquery')
  // ... and so on
}

And your index.html where you test your bundled library will me something like:

<script src='jquery.min.js'></script>
<script src='myLibrary.min.js'></script>
Ematipico
  • 1,181
  • 1
  • 9
  • 14
  • They're not provided externally. They're bundled in but I need to make them available to any seperate js on the page. I sussed it as it happens. expose-loader and not worrying about the reuse of the libraryTarget variable ended my woes – JamesT Jul 07 '17 at 13:33