How to properly import module in javascript with webpack - javascript

I've got a file my-class.js
class MyClass {
constructor(container) {
const myElements = container.querySelectorAll(".class");
for (const myElement of myElements) {
myElement.addEventlistener("click", this.doThings.bind(this));
}
}
doThings() {
// do things
}
}
(() => {
for (const of document.querySelectorAll(".class-holder")) {
new MyClass(container);
}
}
that I import in my main.js file with import "./path-to-file/my-class". But I want to export it instead of create a new instance, and then import it in my main.js file.
But if I export with export { MyClass } and then import with import { MyClass } from "./path-to-file/my-class.js", I get MyClass is declared but it's value is never read. And if I try to run it in my main.js file with new MyClass(); I get Cannot read property querySelectorAll of undefined. How can I properly do the import in my main file so that the code in my-class.js runs correctly?

Related

Typescript migration: Javascript "namespace" with multiple objects

I'm migrating some old js to ts. The file is of form (function implementations omitted for clarity):
// component.js
const Component = {}; // 'namespace' for components
Component.Base = function() {}
Component.A = function() {} // extends Base
Component.A.prototype.doStuffA = function() {}
Component.B = function() {} // extends Base
Component.B.prototype.doStuffB = function() {}
Component.C = function() {} // extends Base
// ... 100 other components, 2000 lines of code
export default Component;
In js, to use the file, I can do:
import Component from './component';
// 1. Instantiate one component
const compA = new Component.A();
// 2. or create multiple components
const threeComps = ['A', 'B', 'C'].map(name => new Component[name]() );
But in ts, I cannot even instantiate one component:
import Component from './component';
const compA: Component.A = new Component.A();
// tsc Cannot find namespace 'Component'
Question: What is the (quick) way to convert component.js into valid typescript, preferably keeping as many type-checks available as possible such
that
const compA: Component.A = new Component.B()
will be flagged as an error by the compiler.
I tried appending the following to the end of file:
namespace Component {
interface A {};
interface B {};
interface C {};
}
This seems to compile into correct javascript, but I would have to add all properties into interfaces. Seems tedious and violation of DRY-principle.
If you are going to migrate to TypeScript, you could immediately take advantage of the class syntax in your component.ts file:
export class Base {
}
export class A {
doStuffA() {}
}
export class B {
doStuffB() {}
}
export class C extends Base {
}
You can consume it using an import alias:
import * as Component from './component';
const a = new Component.A();
Or you can be selective with what you import:
import { A } from './component';
const a = new A();
Export Default / Modules Mixed With Namespaces
On the whole, the experts are saying that export default is a bad thing and that you shouldn't mix modules and namespaces.
You can do it, if you feel you must. here is the example with a namespace / default:
namespace Component {
export class Base {
}
export class A {
doStuffA() {}
}
export class B {
doStuffB() {}
}
export class C extends Base {
}
}
export default Component;
And the use:
import Component from './component';
const a = new Component.A();

How to access method from imported class?

I have a class Scroller:
class Scroller {
constructor() {
super();
}
scroll() {
alert("this works");
}
}
module.exports = Scroller;
imported into my app file...
import '../css/main.scss';
import { nodes } from './nodes';
import { Scroller } from './scrolling';
const s = new Scroller;
nodes.nav.addEventListener('click', () => {
s.scroll();
});
Why won't this console log 'this works' when I click on the nav?
PS I know for sure the event listener is set up the right way, the problem is using that method...
In addition to fixing the parentheses, a problem is
module.exports = Scroller;
You're exporting Scroller as the default export, but
import { Scroller } from './scrolling';
you're trying to import it as a named import. But no such named import exists on scrolling's exports. Import the default object from ./scrolling instead:
import Scroller from './scrolling';

How to import a .d.ts file and how to use class it declared?

I want to import area.js (module testt) into MyModule.ts.
The area.js has a area.d.ts file.
area.d.ts:
import * as $protobuf from "../node_modules/protobufjs/minimal";
/** Properties of a ProtoArea. */
export interface IProtoArea
{
}
/** Represents a ProtoArea. */
export class ProtoArea
{
...
...
}
MyModule.ts:
import ProtoArea = require("../libs/area");
module testt{
export function MyModuleFunc():void
{
console.log("in MyModuleFunc function");
// let msg = ProtoArea.create();
// let buffer = ProtoArea.encode(msg).finish();
// let decode = ProtoArea.decode(buffer);
// console.log(`buffer = ${Array.prototype.toString.call(buffer)}`);
}
export class MyClass
{
public callClassFunc():void
{
console.log("MyClass->callClassFunc()");
}
}
}
Here is LayaSample.ts:
import te = testt.MyModuleFunc;
class GameMain{
constructor()
{
Laya.init(600,400, 0x000000);
console.log("start");
te();
let cls = new testt.MyClass();
cls.callClassFunc();
}
}
new GameMain();
If I add this code in MyModule.ts, it fails on compilation:
Cannot find name 'testt'.
Cannot find namespace 'testt'.
import ProtoArea = require("../libs/bundle");
If Commenting it, compiled without error.
So What's wrong with it?
How can I import it? And How to use class ProtoArea declared in area.d.ts?
I am a fresher of JS and TS. I tried several days. And I found I can import a module like this:
import te = testt.MyModuleFunc;
but no idea to .d.ts..
I tried like these:
import pa = require("../libs/area.d.ts");
import {pa} from "../libs/area";
import ProtoArea as pa from "../libs/area";
import Pa = require("ProtoArea");
require("ProtoArea");
require("../libs/area");
etc.
None of them works.
Thanks for your help.

Typescript - Calling a class exported from another file.

I have a file called searchBar.ts in which contains a init() function that I wish to call in a file called index.ts.
My searchBar.ts file looks like this:
class searchBar {
init() {
console.log('work you C*&*T')
}
}
export let searchBarClass = new searchBar;
I then want to be able to call this function in index.ts. I am currently trying to do this with the below code but init is never found with my intellisense:
import { searchBarClass } from './modules/searchBar';
class Main {
searchBarClass.init()
}
let main = new Main();
export {main}
Later on I then want to wrap the function in a global function that I'll call in the HTML file.
Let me know your thoughts
If you want to export a class and call the init() method on the object instance:
export class SearchBar {
init() {
console.log('work you C*&*T')
}
}
Then accessing it from another file:
import { SearchBar } from './modules/searchBar';
export class Main {
constructor() {
let searchBar = new SearchBar();
searchBar.init();
}
}
let main = new Main();
If you want to access the init() function statically:
export class SearchBar {
static init() {
console.log('work you C*&*T')
}
}
Then accessing it from another file:
import { SearchBar } from './modules/searchBar';
export class Main {
constructor() {
SearchBar.init();
}
}
let main = new Main();

how to use a function from another js file in reactjs?

i have a file something.js which has a function:
someFunction: function(arg1, arg2){
//code blocks
}
In my app.js file i want to call this function in the app class. I have imported the something.js file like this import { someFunction } from './something.js';. Now i am trying to use it in a function in the app class
var res = someFunction("abc", 2);
console.log(res);`
i am getting a error Uncaught TypeError: (0 , _something.someFunction) is not a function
Some help would be appreciated.
You need to write it like this:
something.js file -
module.exports = {
A: funtion(){
},
B: funtion(){
}
}
Then import it like this:
import {A} from 'something';
Or use it like this:
something.js file -
export A(){
}
export B(){
}
Then import it like this:
import {A} from 'something';
Read this article: https://danmartensen.svbtle.com/build-better-apps-with-es6-modules
In order to import something, you need to export it from the other module.
For example, you could export class YourComponent extends React.Component in something.js.
Then in the other file you can import { YourComponent } from './something'
You could, for example, in something.js do something like
const MyClass = {
methodName() { return true; }
}
export { MyClass as default } // no semi-colon
Then in the other file you could
import WhateverIWant from 'something';
WhateverIWant.methodName(); // will return true
Edit:
An in-depth explanation with lots of examples is available here.
You could either do: in your something.js file: module.exports = function(){}..
and in your app.js file:
const functionName = require('./path_to_your_file');
Or export somethingFunction = {} and in app.js:
import { somethingFunction } from './path_to_your_file'
Or last: export default somethingFunction = {} and in app.js:
import whateverNameYouChoose from './path_to_your_file'
Let me know if that did the trick! :)
In your something.js file, you can add export someFunction near the bottom of the file. This will then allow you to import that function using the import { someFunction } from './something.js'; you have earlier.

Categories