Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack - How to load non module scripts into global scope | window

so i have a few vendor files that i need to run from window scoped (it's a bunch of window scoped functions) plus i have some polyfills that i would like to bundle into the vendor bundle as well.

So i tried something like this:

new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'js/vendor.min.js',
    minChunks: Infinity,
})

entry: {
    'vendor' : ['./vendor.js', './vendor2.js', './polyfills.js']
}

Now when i run my webpack build it does generate my vendor bundle but it's all wrapped in a webpackJsonP wrapper so the functions are not accessible on the window scope.

I've also looked at using something like the ProvidePlugin but i couldn't make that work at all since i don't have a defined name like jQuery where everything is mapped under.

Is this even possible in webpack?

like image 250
Mick Feller Avatar asked Feb 26 '18 22:02

Mick Feller


1 Answers

Use the script-loader plugin:

If you want the whole script to register in the global namespace you have to use script-loader. This is not recommend, as it breaks the sense of modules ;-) But if there is no other way:

npm install --save-dev script-loader

Webpack docs

This loader evaluates code in the global context, just like you would add the code into a script tag. In this mode every normal library should work. require, module, etc. are undefined.

Note: The file is added as string to the bundle. It is not minimized by webpack, so use a minimized version. There is also no dev tool support for libraries added by this loader.

Then in your entry.js file you could import it inline:

import  "script-loader!./eluminate.js"

or via config:

module.exports = {
  module: {
    rules: [
      {
        test: /eluminate\.js$/,
        use: [ 'script-loader' ]
      }
    ]
  }
}

and in your entry.js

import './eluminate.js';

As I said, it pollutes the global namespace:

enter image description here

like image 130
Legends Avatar answered Sep 29 '22 13:09

Legends