I'm trying to develop an API javascript package that developers can use to access and interact in my application. I want the developers to access the APIs by using a CDN script at the head of their own application and call the needed resources where appropriate. I similar example to what I'm attempting is google's recapthca. The idea is as follows:
- Load the package from the CDN
<script src="https://cdn.example.com/package.js"></script>
- Use the library from the package as needed
package.init('demo-button', {
resoruceId: '506e2f7c-eaef-4136-9ba2-8ccb116a0480',
});
However, I'm struggling to make the package
available in the client host, and I kept getting the error Uncaught ReferenceError: package is not defined
.
This is my src/index.js file:
const package = (function () {
const init = function (buttonId, config) {
console.log('Initializing Orionis with config:', config);
};
const publicAPI = {
init: init
};
return publicAPI;
})();
export default orionis
This is my package.json file:
{
"name": "package-example",
"version": "1.0.0",
"private": true,
"description": "CDN SDK",
"license": "ISC",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js && npx tailwindcss -i ./src/index.css -o ./src/components/main.css --watch"
},
"dependencies": {
"@headlessui/react": "^1.7.17",
"@heroicons/react": "^2.0.18",
"@tinymce/tinymce-react": "^4.3.0",
"axios": "^1.6.0",
"express": "^4.18.2",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/core": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"@babel/preset-react": "^7.22.15",
"@tailwindcss/aspect-ratio": "^0.4.2",
"@tailwindcss/forms": "^0.5.7",
"@tailwindcss/typography": "^0.5.10",
"babel-loader": "^9.1.3",
"css-loader": "^6.8.1",
"style-loader": "^3.3.3",
"tailwindcss": "^3.3.5",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4"
}
}
This is my server.js file:
const express = require('express')
const path = require('path');
const app = express()
const port = 4000
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use(express.static('dist'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
This is my webpack.config.js file:
const path = require('path');
module.exports = {
target: 'web',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
library: 'package',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
Any guidance or advice on how to solve this will be helpful