Webpack 4: How to call a global function with arguments? - javascript

I'm writing a new build script for my project using Webpack 4, so far, I have not faced any issue until today, when I have to call a global function with parameters.
Below is an example, I did without parameters for Google reCaptcha:
const enableFormButton = () => {
var elements = "#form_submit_btn, #form_submit_btn_alt";
$(elements).removeAttr("disabled");
$(elements).css({"cursor":"pointer"});
$(elements).removeClass("button button-3d button-red button-small").addClass("button button-3d button-green-invert button-small");
}
const recaptcha = document.querySelectorAll(".g-recaptcha");
recaptcha.forEach((captcha) => {
captcha.setAttribute('data-callback', 'enableFormButton');
});
export { enableFormButton }
and in my entry index.js file, it would look like this:
import {enableFormButton} from './some_js_file'
window.enableFormButton = enableFormButton
Now, this is what I tried with a global function with parameters:
const exampleFunction = (arg1) => {
// do something here
}
export {exampleFunction}
and in the index.js file:
import {exampleFunction} from './some_js_file'
window.exampleFunction = exampleFunction
I tried it, there are no build errors but I get an error in the console saying
"Uncaught TypeError: exampleFunction is not a function"
Any idea on how to solve this? Btw, I'm kind of new to using Webpack.

Thanks to #CertainPerformance's tip, I added the export keyword to the function exampleFunction(arg1), which should look like this:
export exampleFunction(arg1){
// something
}
Imported the function to another .js file:
import {exampleFunction} from './somescript';
And then, it worked! :)
So turns out, I learnt something for the day!

Related

'X Is not a function' in CommonJS

I've got the following code I transformed from a Trypescript, ESM-syntax based file to a Javascript, CJS-syntax file.
const apiClientFactory = require("#vue-storefront/core");
function onCreate(settings) {
return {
config: settings,
client: {},
};
}
const getPrice = () => {
console.log("$55,98")
}
const { createApiClient } = apiClientFactory({
onCreate,
api: {
getPrice,
},
});
module.exports = {
createApiClient,
};
I can not seem to find if the error "apiClientFactory is not a function" originates from old ESM-based code. Or that the function isn't called properly. However, apiClientFactory is correctly imported (ESM syntax)
What are you trying to achieve with this?
Because the whole Vue Storefront project uses TypeScript, so I recommend you to use it and follow the procedures and code standards that we are using.
To find a good example on the API please check the code for the integrations of Magento or Vendure.

Datepickk library not define using webpack

i'm building a calendar module on my current project using Datepickk library. But when i tried to initialize it, it always show "ReferenceError: Datepickk is not defined" error.
this is my code:
- calendar.js
const schoolCalendar = () => {
//Initialize
var datepicker = new Datepickk();
datepicker.show();
}
export default schoolCalendar;
main.js file
import schoolLogin from "./pages/school/login/_login";
import schoolCalendar from "./pages/school/_calendar/_calendar";
function loadOnDasboardPages()
let pageLocation = document.body.getAttribute('data-dashboard');
switch (pageLocation) {
case "teacher":
dashboardTeacher();
break;
case "school-calendar":
schoolCalendar();
break;
default:
return null;
}
}
loadOnDasboardPages();
the error:
"ReferenceError: Datepickk is not defined" appeared on console when i tried to run it.
what is the cause for this error as i already followed its documentation.
How do i fix this issue? so i can use this library for my project.
thank you very much in advance.
Assuming you use npm to install datepickk, you need to import the library to use it. The same goes for any library installed with npm.
So your file calendar.js should look like:
import Datepickk from 'datepickk';
const schoolCalendar = () => {
//Initialize
var datepicker = new Datepickk();
datepicker.show();
}
export default schoolCalendar;
or
import "datepickk/dist/datepickk.css";
import Datepickk from "datepickk/dist/datepickk";
const schoolCalendar = () => {
//Initialize
var datepicker = new Datepickk();
datepicker.show();
}
export default schoolCalendar;
Sample code: https://codesandbox.io/s/optimistic-shannon-ikt4e

Jest: Testing API Methods from Intercom

I am having trouble understanding what the testing flow would be for testing functions which use functions loaded from a JavaScript library from Intercom.
My method looks like this:
export const generateButton = (handleOnClick) => {
case "moo":
return <button onClick={() => Intercom('show')}>Sign Up</button>
default:
return 'moo'
The error I get when running this is:
ReferenceError: Intercom is not defined
So I figured it out, I needed to add a new file and point jest set up on package.json to it like so (the file added is mockObject)
"setupFiles": [
"./config/jest/setupJest.js",
"./config/jest/mockObject.js"
],
then in the file itself has this in it
global.Intercom = () => {
console.log('Intercom called')
}
If I understand what you're trying to do then create a dummyFunction to replace Intercom in your tests. Something like this...
const Intercom = jest.fn();
describe('button click', () => {
it('Intercom is called correctly', () => {
// whatever component contains the button should be mounted
const wrapper = mount(<YourComponentHere />);
// you may need to add a class to target the specific button
wrapper.find('button').simulate('click');
expect(dummyFunction).toHaveBeenCalledWith('show');
expect(dummyFunction).toHaveBeenCalledTimes(1);
});
});

How to use Vue Plugins Correctly? <PluginName> is not defined

Im learning to make Vue Plugin, based on https://v2.vuejs.org/v2/guide/plugins.html,
this is my simple code:
plugin1.js:
AlertPlugin.install = function (Vue, options) {
Vue.prototype.$classicalert = function (message) {
alert(message)
};
};
app.js:
window.Vue = require('vue');
import AlertPlugin from './plugin1.js'
Vue.use(AlertPlugin);
const app = new Vue({
el: '#app',
render: h => h(Main)
});
when im trying to run it, the web page become blank, and error AlertPlugin is not defined.
please help?
In your plugin1.js file, you are attempting to set the install property of the AlertPlugin object, which (as the error says) is not defined.
Your plugin1.js file should look like this:
export default {
install: function (Vue, options) {
Vue.prototype.$classicalert = function (message) {
alert(message)
};
}
}
This defines a default object to export containing a property install. When you import this object as AlertPlugin, like you are doing in app.js, it will result in an AlertPlugin object with the install property you defined in the plugin's file.

Load JavaScript file in angular2 app

I'm working on a angular2 application written in TypeScript.
This works:
I have a module called plugin-map.ts which looks something like this:
import { Type } from '#angular/core';
import { SomeComponent } from './plugins/some.component';
export const PluginMap: { [key: string]: Type<any> } = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': SomeComponent
};
It gets transpiled to a plugin-map.js which looks something like this:
"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map
And in other modules I'm importing my PluginMap like this:
import { PluginMap } from './plugin-map';
What I want:
Now I want to create plugin-map.js at runtime when my server starts. So I want to get rid of my plugin-map.ts and instead have only a (generated) plugin-map.js. And I don't want to have any transpile-time dependencies to that plugin-map.js.
What I tried:
In modules where I need to access the PluginMap I replaced the import statement with a declaration like this:
declare const PluginMap: { [key: string]: Type<any> };
Now of course at runtime I get a Error: (SystemJS) 'PluginMap' is undefined. So my next step was to load plugin-map.js explicitly from my index.html like this:
...
<script src="js/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('./app/plugins/plugin-map.js').catch(function (err) { console.error(err); });
System.import('app').catch(function(err){ console.error(err); });
</script>
...
When I start my application I can see that the browser actually requests the plugin-map.js file. But I still get the Error: (SystemJS) 'PluginMap' is undefined.
Question:
How/where do I have to load my generated plugin-map.js so that this works?
I had to make sure that PluginMap is available in the global context. So the generated plugin-map.js has to look like this:
var some_component_1 = require('./plugins/some.component');
PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
and not like this:
"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map
Now it seems to work.

Categories

Resources