In Webpack, you may occasionally need to load non-module scripts (i.e., scripts that do not adhere to CommonJS or ES6 module specifications) into the global scope or the window object. This can be achieved through several methods; here are some examples:
Using expose-loader
Webpack's expose-loader allows you to expose modules to the global object. For example, if you want to expose a global variable named someLibrary to the global scope, you can configure it in module.rules as follows:
javascript// webpack.config.js module.exports = { // ... other configurations ... module: { rules: [ { test: require.resolve('path-to-non-module-script'), use: [{ loader: 'expose-loader', options: { exposes: ['someLibrary'], }, }], }, ], }, // ... other configurations ... };
The above configuration will expose the script pointed to by path-to-non-module-script as the global someLibrary object.
Using script-loader
script-loader executes the script in the global context, similar to using a <script> tag. This means the script can affect the global scope. Adding script-loader to your Webpack configuration rules is shown as follows:
javascript// webpack.config.js module.exports = { // ... other configurations ... module: { rules: [ { test: require.resolve('path-to-non-module-script'), use: [{ loader: 'script-loader' }], }, ], }, // ... other configurations ... };
Using imports-loader
Using imports-loader can set the this context inside the module to the window object, which can be helpful in certain cases, especially when the script expects its context to be the global context.
javascript// webpack.config.js module.exports = { // ... other configurations ... module: { rules: [ { test: require.resolve('path-to-non-module-script'), use: [{ loader: 'imports-loader', options: { wrapper: 'window', }, }], }, ], }, // ... other configurations ... };
Manually Mounting to window
If you don't want to use loaders, you can manually mount libraries or features to the window object within the module system. For example:
javascript// In your entry script or anywhere suitable import * as myNonModuleLibrary from 'path-to-non-module-script'; // Mount the library to the window object window.myNonModuleLibrary = myNonModuleLibrary;
This approach requires you to explicitly know the object or library you want to mount and manually perform the mounting.
Summary
Loading non-module scripts into the global scope is a common requirement in the Webpack environment. Depending on your specific situation, you can choose to use expose-loader, script-loader, imports-loader, or manually mount the scripts to the window object. Each method has its applicable scenarios, and you should choose the most suitable approach based on project requirements and script characteristics.