Reputation: 77
I'm new to webpack and can't figure out how to expose a class constructor to the browser’s global namespace. For example, how do I configure webpack so that the code below prints “hello world” in the console? I've tried using exports-loader
, expose-loader
, and script-loader
without success.
main.js
class MyClass {
print() {
console.log('hello world');
}
}
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="./dist/bundle.js"></script>
<script>
myClass = new MyClass;
myClass.print();
</script>
</body>
</html>
Upvotes: 4
Views: 2789
Reputation: 525
Current webpack API uses library
object (or string, in that case it is treated as name
) to expose the namespace to the global scope. You can rely on defaults and simply do something like
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
module.exports = {
context: path.resolve(__dirname),
entry: './src/index.js', //path to a file that exports things you need
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack-numbers.js',
library: 'MyAwesomeLib'
},
};
and you will find the ./src/index.js
exported contents at window.MyAwesomeLib
. You can be more specific (see docs):
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'window', //umd, global, ...
},
},
};
but then you might experience empty objects if not configured properly. Relying on default setup works nicely.
Upvotes: 1
Reputation: 4766
You can either:
a) Expose your function (class) explicitly:
main.js
class MyClass {
print() {
console.log('hello world');
}
}
window.MyClass = MyClass;
Then you can call your constructor from global object by referencing MyClass
directly.
b) Configure webpack to expose your exports in a global object as follows:
webpack.config.js
module.exports = {
output: {
library: 'someName',
libraryTarget: 'umd',
globalObject: 'this'
}
}
Then you can call your constructor by referencing exported function (class) in a global variable configured as library
option in above config file. In this example someName.MyClass
. For this to work you must export the function in main.js file, as shown below.
main.js
export class MyClass {
print() {
console.log('hello world');
}
}
Refer to webpack output configuration for more specifics.
Upvotes: 8