'Webpack: How do I get functions working globally?
For the past 3-4 years, I've been using gulp to build a production JS file from a series of disparate JS files. I'm not using React or any other libraries, and my only assets are JS files written entirely in vanilla JS. With the gulp-built file, I'm able to call functions throughout my code without any issues - my files can talk to each other, so to speak.
But now, I'm wanting to migrate to from gulp to webpack. And for such a simple use case, I'm running into trouble when it comes to global scope. Whenever I test the bundled file in the browser, I can see undefined errors for functions in my file.
I realize that this outcome is to be expected, as webpack modularizes code a bit differently than gulp to prevent collisions. But surely there's a way to modify my webpack configuration so that it works like gulp has for me?
I've read through posts about similar issues and also reviewed the webpack docs to try and solve this on my own, but no luck.
Here's what I've tried:
- Explicitly assigning functions to
window.
function foo() {
...
}
window.foo = foo;
While this technically works, it's not a sustainable approach given how many functions are in my code. I don't want to be in the business of manually assigning each function to window.
Changing the value of
useBuiltIns: Just for sh*** and giggles, I tried"usage"and"entry"in addition to the default option of"false"-- none of this worked.Adding
node.global: trueto mymodule.exports. This didn't work either. Not to mention, I think this approach is outdated as of webpack 5.
Does anyone have guidance for how to get webpack working the way I need it to? Below is my current config.
webpack.config.js
const path = require('path');
const glob = require('glob');
const apis = glob.sync('./code/api/*.js');
const legacy = glob.sync('./code/legacy/*.js');
const standardTags = glob.sync('./code/standardTags/*.js');
const endpoints = glob.sync('./code/core/endpoints/*.js');
const auxFunctions = glob.sync('./code/aux-functions/*.js');
const sourceArray = [...apis, ...legacy, ...standardTags, ...endpoints, ...auxFunctions];
const presets = [
[
"@babel/preset-env",
{
"corejs": {
"version":3
},
"useBuiltIns": "usage",
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1",
"ie": "9"
}
}
]
];
module.exports = {
entry: [...sourceFileArray],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/nep-build.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets
}
}
}
]
},
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
