Webpack - How to load non module scripts into global scope | window
Both above solutions will have issues when the site is enforcing some content-security-policy(CSP) rules due to use of unsafe eval expressions, which is absolutely a good thing. (always treat security as first-class citizen in web ;))
Alternative solutions i have found so far are, assuming you are also working on a legacy codebase and having this kind of need
For UMD
modules, consider import-loader, an example
test: require.resolve('jquery'),
use: {
loader: 'imports-loader',
options: {
wrapper: {
thisArg: 'window',
args: {
module: false,
exports: false,
define: false,
},
},
},
},
},
For CJS
modules export to global namespace, consider expose-loader.
Also if you have time, give webpack shimming a read.
script-loader should-not be used anymore. You can use raw-loader instead:
npm install --save-dev raw-loader
And:
import('!!raw-loader!./nonModuleScript.js').then(rawModule => eval.call(null, rawModule.default));
I'm using !!
before raw-loader
because I'm in the case described in the documentation:
Adding
!!
to a request will disable all loaders specified in the configuration
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: