Hope you're doing well. I'm currently working on a JavaScript module that I plan to load via a Content Delivery Network (CDN) using the URL https://x.com/my-script.js. However, I've hit a snag despite trying various webpack configurations.
Environment :
To clarify, when I simplify my module without webpack, like so:
const randomGenerator = {
generateRandomNumber: function(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
};
export default randomGenerator;
...the import works like a charm. Here's how I import and use the module:
import randomGenerator from 'https://x.com/my-script.js';
console.log(randomGenerator.generateRandomNumber(1, 100));
Responses in the following Stack Question tels you how to export default and import named-default-javascript
But when I throw webpack into the mix, I get this error:
requested module 'https://x.com/my-script.js' does not provide an export named 'default'
I suspected it's a webpack configuration issue, so I consulted the Webpack documentation, which recommends configuring output like so for a Universal Module Definition which are capable of working everywhere, be it in the client, on the server or elsewhere as noted in github :
output: {
filename: 'compactedModule.js',
path: path.resolve(__dirname, 'dist'),
library:'randomGenerator',
libraryTarget: 'umd'
}
I also checked out how Axios axios.min.js is built, and it's similar
Finally here is my full webpack config file :
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: '../src/test.js',
output: {
filename: 'compactedModule.js',
path: path.resolve(__dirname, 'dist'),
library:'randomGenerator',
libraryTarget: 'umd'
},
plugins: [
new CleanWebpackPlugin(),
],
};
Note that for every changement I make to the bundle module I clear browser cache
Any help would be greatly appreciated.
Thanks in advance!
Solved by adding the script tag in the index.html file
<script type="text/javascript" src="https://x.com/my-script.js" defer></script>
And then for usage inside the component you can call the function as follow
window.randomGenerator.generateRandomNumber
but note that the script will be loaded in each page load I will post another answer once I find out how to load only in a specific page inside one vuejs component