Why components defined by "customElements.define()" are not globally usable? - javascript

I am working on a Svelte project, but it contains some web components.
The issue I am facing is that some web components defined by the customElements.define() Typescript function are not usable unless I import them specifically in the user component.
For example, a web component is defined in the following way:
// File name is oneWebComponent.js
export class OneWebComponent extends HTMLElement {
...
customElements.define('one-web-component', OneWebComponent);
}
Then, there is another JS file, which contains a "factory" function that creates different types of Web Components:
export const createElement = (tagName) => {
return document.createElement(tagName);
}
If I call it like createElement('one-web-component'), the resulting component is not really the one defined in OneWebComponent. I know that because the functions defined there are not callable (error: XXX is not a function).
But if I import oneWebComponent.js in the factory file like below, it works correctly:
// This line is newly added:
import './oneWebComponent.js';
export const createElement = (tagName) => {
return document.createElement(tagName);
}
That means, if I have multiple types of web components, and the factory function is called in multiple places, I will have to import each type of web component in each place, which is tedious.
I wonder if there is a way to just make the components defined by customElements.define() globally usable?
That means, no imports needed, just passing the tag name into document.createElement() and it will create the web component correctly.
Am I missing any configs?
Thanks in advance!

As #Bergi pointed out, the customElements.define() function is not executed if the file is not imported anywhere.
So I only needed to import all of the web components in the top level of the app, a file like app.svelte or main.js for example, then the function will run, and the tags are defined and usable across the app.

Related

Importing / exporting Javascript Object Properties

I support a relatively complex legacy codebase, but am looking to modernise it a little by bringing in Webpack so that we'd have import & export capabilities in JS.
The problem I'm having is that we use a global object called App where we define and add different properties depending on the page. So for example we have the following file where we instantiate App (loaded on all pages):
app.js
const App = (() => {
const obj = {
Lib: {},
Util: {},
// etc
}
return obj;
})();
Then in another file we add to App.Lib just for the specific page that needs it:
lazyload.js
App.Lib.Lazyload = (() => {
// lazyload logic
})();
We simply concatenate the files during the bundling process, but obviously this is not ideal as none of the files have no knowledge of what goes on outside of it.
Exporting only seems to work for the top level object (where the object is defined), so anything I add to it elsewhere cannot be exported again. For example if I add export default App.Lib.Lazyload; at the end of lazyload.js and then try to import it elsewhere it will not import the Lazyload property.
Is there any way to get this to work without major refactor? If not, would you have any suggestions about the best way to handle it?
I don't think you can import Object.properties in JS. If you want to bundle specific packages (say Lazyload) for packages that need them, you might try:
//lazyload.js
export const LazyLoad = {
//lazyload logic
}
then somewhere else...
import {LazyLoad} from 'path/to/lazyload.js';
// assuming App has already been created/instantiated
App.Lib.Lazyload = LazyLoad;
Using Export Default...
//lazyload.js
const LazyLoad = {};
export default LazyLoad;
then...
import LazyLoad from 'path/to/lazyload.js';
App.Lib.LazyLoad = LazyLoad;
You can find help with Imports and Exports at MDN.

How does import work with react?

My broader question is does an import of a module get shared between two components and why?
First what do I know about import. You can import in two different ways.
1.
At the top of your file which loads the imported module into a variable which you then can use.
import Highcharts from './highcharts'
// create a chart
Highcharts.Chart()
2.
Or dynamically anywhere in your code which returns a promise:
import('./highcharts').then((response) => {
// create chart
response.Chart();
});
But there is this weird behavior I don't understand when using import with react. If I have the following component:
import React, {Component} from 'react';
import Highcharts from 'highcharts/js/highcharts';
export default class Chart extends Component {
state = {
chartOptions: {
// my chart options and data
}
}
componentDidMount() {
if(this.props.extendFunc) {
import('highcharts/js/modules/funnel.src.js').then((funnelModule) => {
funnelModule(Highcharts)
})
}
Highchart.Chart('myChart', this.state.chartOptions)
}
render() {
<div id="myChart" />
}
}
I use the component from above twice. Now there is this behavior that both components use the same import e.g. the import of Highcharts does not happen twice. I noticed this because with Highcharts there is the option of extending the functionality.
If I for example extend the functionality for Chart 1 by passing a prop to extend it, the functionality of Highcharts is also extended in Chart 2, although I didn't pass a prop to extend the functionality.
import React, {Component} from 'react';
import Chart from './Chart';
export default class Dashboard extends Component {
render() {
return (
<div>
<Chart extendFunc={true}> Chart 1 </Chart>
<Chart> Chart 2 </Chart>
</div>
)
}
}
What causes this behavior? Is this react or is this just the way import works? Are imports global for multiple instances of the same component? Or are imports of a node module the same for the whole application?
What causes this behavior? Is this react or is this just the way import works? Are imports global for multiple instances of the same component? Or are imports of a node module the same for the whole application?
This is the way imports work. When you import something for the first time, the file is run and the exported values from it are returned back to the one importing it. When something is imported again, those same exports are reused and returned. Node JS modules work the same way.
Sometimes this behavior is helpful, firstly for performance to avoid unnecessarily re-running the same file over again, and also if the module wants to store some internal state. For example, counting the number of times a function is called from anywhere in the application.
In cases like this, where you need a single instance of something for each script, modules will usually give you a way to actually make an instance of that thing. For example, I might have a logging module, which exports a Logger class, then I can make new instances of that class for each component, and configure each logger separately.
For your case, look in the docs to see if there's a way to make per-component instances of Highcharts and extend that individual instance with the functionality you need.
When you extend <Chart /> with a prop extendFunc it will be extended in your Chart Component and not in your "new" Component.
That means, if you call the component, it will always have the props you gave it, but you will not have to use them (if there are not set as required).

Importing javascript file for use within vue component

I am working on a project that requires using a js plugin. Now that we're using vue and we have a component to handle the plugin based logic, I need to import the js plugin file within the vue component in order to initialize the plugin.
Previously, this was handled within the markup as follows:
<script src="//api.myplugincom/widget/mykey.js
"></script>
This is what I tried, but I am getting a compile time error:
MyComponent.vue
import Vue from 'vue';
import * from '//api.myplugincom/widget/mykey.js';
export default {
data: {
My question is, what is the proper way to import this javascript file so I can use it within my vue component?
...
Include an external JavaScript file
Try including your (external) JavaScript into the mounted hook of your Vue component.
<script>
export default {
mounted() {
const plugin = document.createElement("script");
plugin.setAttribute(
"src",
"//api.myplugincom/widget/mykey.js"
);
plugin.async = true;
document.head.appendChild(plugin);
}
};
</script>
Reference: How to include a tag on a Vue component
Import a local JavaScript file
In the case that you would like to import a local JavaScript in your Vue component, you can import it this way:
MyComponent.vue
<script>
import * as mykey from '../assets/js/mykey.js'
export default {
data() {
return {
message: `Hello ${mykey.MY_CONST}!` // Hello Vue.js!
}
}
}
</script>
Suppose your project structure looks like:
src
- assets
- js
- mykey.js
- components
MyComponent.vue
And you can export variables or functions in mykey.js:
export let myVariable = {};
export const MY_CONST = 'Vue.js';
export function myFoo(a, b) {
return a + b;
}
Note: checked with Vue.js version 2.6.10
try to download this script
import * from '{path}/mykey.js'.
or import script
<script src="//api.myplugincom/widget/mykey.js"></script>
in <head>, use global variable in your component.
For scripts you bring in the browser way (i.e., with tags), they generally make some variable available globally.
For these, you don't have to import anything. They'll just be available.
If you are using something like Webstorm (or any of the related JetBrains IDEs), you can add /* global globalValueHere */ to let it know that "hey, this isn't defined in my file, but it exists." It isn't required, but it'll make the "undefined" squiggly lines go away.
For example:
/* global Vue */
is what I use when I am pulling Vue down from a CDN (instead of using it directly).
Beyond that, you just use it as you normally would.
I wanted to embed a script on my component and tried everything mentioned above, but the script contains document.write. Then I found a short article on Medium about using postscribe which was an easy fix and resolved the matter.
npm i postscribe --save
Then I was able to go from there. I disabled the useless escape from eslint and used #gist as the template's single root element id:
import postscribe from 'postscribe';
export default {
name: "MyTemplate",
mounted: function() {
postscribe(
"#gist",
/* eslint-disable-next-line */
`<script src='...'><\/script>`
);
},
The article is here for reference:
https://medium.com/#gaute.meek/how-to-add-a-script-tag-in-a-vue-component-34f57b2fe9bd
For anyone including an external JS file and having trouble accessing the jQuery prototype method(s) inside of the loaded script.
Sample projects I saw in vanilla JS, React and Angular were simply using:
$("#someId").somePlugin(options)
or
window.$("#someId").somePlugin(options)
But when I try either of those in my VueJS component I receive:
Error: _webpack_provided_window_dot$(...).somePluginis not a function
I examined the window object after the resources had loaded I was able to find the jQuery prototype method in the window.self read-only property that returns the window itself:
window.self.$("#someId").somePlugin(options)
Many examples show how to load the external JS file in VueJS but not actually using the jQuery prototype methods within the component.

How can I access angular-redux store from child module?

In my angular app I use angular-redux for application state management. In my main module I defined my redux store. Like this:
export class MainModule {
constructor(private ngRedux: NgRedux<MainAppState>,
private devTools: DevToolsExtension) {
let enhancers = [];
if (environment.production === false && devTools.isEnabled()) {
enhancers = [...enhancers, devTools.enhancer()];
}
this.ngRedux.configureStore(
reducer,
{} as MainAppState,
[],
enhancers);
}
}
I created new child module, which contains some components. These components should access to application state. In one of these components I access via #select to store, but this doesn't work. Here is how I access to store:
export function getLanguage(state: LanguageState) { return state.userLanguage; }
And this code I have in my ChildComponent class:
export class ChildComponent implements OnInit {
#select(getLanguage) savedUserLanguage$: Observable<LanguageState>;
// more code
}
How can I access to application state store from child modules? What should I import in child module? Will It be better to create own module only for redux store handling? Maybe I forgot something?
I use Angular v4 and #angular-redux/store v6.
I'd recommend creating a separate module that just contains your store, e.g. StoreModule. You can then import your StoreModule into all your child modules and access your store from there.
This is the way they go in the official example app:
StoreModule: https://github.com/angular-redux/example-app/blob/master/src/app/store/module.ts
Child Module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/module.ts
Component in child module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/page.ts
I was thinking about refactoring some ugly old JavaScript code that uses prototypal inheritance into an Angular 7+ project. I was asking myself pretty much the same question. Inspired by my udemy Angular course, I tried an experiment with a ngrx store and lazy loaded modules.
(Keep in mind that ngrx is SIMILAR to #angular-redux, but it's NOT the same thing. See https://ngrx.io/docs for details.)
Here it is.
I create the store in the main module with StoreModule.forRoot and in each lazy loaded module, I create a reference to the store with StoreModule.forFeature.
(See https://ngrx.io/api/store/StoreModule for details.)
When I dispatch actions on the store with the lazy loaded components, those actions (and corresponding reducers) seem to change the value to which the main app component subscribes.
Also, when I dispatch actions on the store with the main app component, those actions (and corresponding reducers) seem to change the value to which the lazy loaded components subscribe.
Also, it's hard to explain what I did in a simple 200-500 character block so I had to use a github project.

React-Native: Accessing methods in file included using require()

When splitting methods into seperate class files in react native how do I then access those classes from another file?
For example in included.js I have the following:
'use strict'
import React, { Component } from 'react';
import {
AsyncStorage,
} from 'react-native';
var myClass = React.createClass({
doStuff: function(){
return 'Hello';
},
render: function(){ //This is required???
},
})
module.exports = myClass;
In my index.ios.js file I have:
var myClass = require('./included');
How do I now call a function from myClass?
I'm new to using react native and suspect my current approach is not ideal but haven't found a clear example of how to seperate my code. For example external API calling methods in a class from the classes that build the views in my app.
You can't just simply call a method in another component. React has its own design pattern and it does not allow that.
Accodring to React docs:
For communication between two components that don't have a
parent-child relationship, you can set up your own global event
system. Subscribe to events in componentDidMount(), unsubscribe in
componentWillUnmount(), and call setState() when you receive an event.

Categories

Resources