Javascript module import fails - why? - javascript

I'm a javascript newbie and I'm trying to figure out why this import statement fails. I don't know if this is relevant but I'm doing this in the context of a Create React app with its default webpack setup. I have these files:
TestClass.js
export default class TestClass {
sayHello() {
console.log("Hello World.");
}
}
TestModule.js
import TestClass from "./TestClass";
module.exports = {
MyExport: {
doSomething: function() {
let testClass = new TestClass();
testClass.sayHello();
}
}
}
And then my main React Application file, App.js:
import React, { Component } from "react";
import "./App.css";
import { MyExport } from "./TestModule"
class App extends Component {
constructor(props) {
super(props);
MyExport.doSomething();
... bla bla bla ...
}
When I attempt to run this in Node.js, it returns
Failed to compile.
./src/App.js
Attempted import error: 'MyExport' is not exported from './TestModule'.
What am I doing wrong?

You are mixing es6 modules with Commonjs style imports. Your TestModule should be exported as follows:
import { TestClass } from "./TestClass";
export const MyExport = {
doSomething: function () {
let testClass = new TestClass();
testClass.sayHello();
}
};
This should work while allowing the rest of your code to remain the same

You can try this:
import { TestClass } from "./TestClass";
const Object = {
MyExport: {
doSomething: function() {
let testClass = new TestClass();
testClass.sayHello();
}
}
}
export default MyExport
As you are using two different type of import export
Or if you have to use module.exports you can try this:
import { TestClass } from "./TestClass";
module.exports = function () {
return {
MyExport: {
doSomething: function() {
let testClass = new TestClass();
testClass.sayHello();
}
}
}
}
You can try exporting function instead of object

Related

Calling a variable from a javascript file returns an undefined: Ionic

I'm using the Ionic framework and I want to call a variable from a javascript file, but it returns undefined for the variable and prints the console inside the file.
javascript file:
console.log('Hi!')
var test = "Hello";
typescript file:
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
test:any='j';
constructor (){
this.test= testfile.test;
console.log('Hello from typescript', this.test);
}
}
The Result
Hi
Hello from typescript undefined
You should export the variable from your JavaScript file for the value to be accessible inside the TypeScript file.
So inside your "src/assets/js/customers" file it should be
export var test = "Hello";
OR
var test = "Hello";
export test;
If this is not a default export you need to import it like
import * as { testfile } from "src/assets/js/customers"
//Dont forget to export your JS file to use in other files.
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
constructor (
public test: testfile.test
){}
async ngOnInit(){
console.log('Hello from typescript', test);
}
}
//or
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
async ngOnInit(){
this.test = testfile.test
console.log('Hello from typescript', this.test);
}
test
}

ReactJS: How to use refs() for setting 'innerHTML' inside component?

Here I am trying to set innerHTML from my Test.js on render inside my componentDidMount. On the process I am getting errors of Unhandled Rejection (TypeError): Cannot set property 'innerHTML' of null .
I have gone through few questions where it defined to use refs() but unfotunately not able to use this in my case.
Any suggestion how can I use refs() here in my example?
demo Test.js
function updateList() {
const json = JSON.parse(localStorage["values"]);
if (json) {
picture = json.picture;
if (picture) {
userPicture = picture.name;
}
}
console.log(userPicture, "userPicture");
document.getElementById('picture').innerHTML = userPicture;
}
async function getAll () {
await updateList();
}
export default {
getAll
};
TestComponent.js
import React from 'react';
import Test from './Test';
class TestComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
Test.getAll();
}
render() {
return (
<div className="test-item" >
<div className="test-picture" id="picture"> </div>
</div>
);
}
};
export default (injectIntl(TestComponent));
I believe this is what you want.
Code sandbox url - https://codesandbox.io/s/fervent-surf-n72h6?file=/src/index.js
App.component
import React from "react";
import { render } from "react-dom";
import Test from "./Test";
class App extends React.Component {
constructor(props) {
super(props);
this.divRef= React.createRef();
}
componentDidMount() {
Test.getAll(this.divRef);
}
render() {
return (
<div className="test-item">
<div className="test-picture" ref={this.divRef} id="picture">
Hello from component
</div>
</div>
);
}
}
const container = document.createElement("div");
document.body.appendChild(container);
render(<App />, container);
Test.js
function updateList(ref) {
ref.current.innerHTML = "Hello from Test.js";
}
async function getAll(ref) {
await updateList(ref);
}
export default {
getAll
};

Enzyme shallow returns undefined for renderless component

This is my js file
import React, { Component } from 'react';
export default class ProjectStore extends Component {
static lodingCount = 0;
constructor(props) {
super(props);
}
static setLodingCount(countValue){
ProjectStore.lodingCount = countValue;
}
static getLodingCount(){
return ProjectStore.lodingCount;
}
}
I wrote a test case for the same like below:
import React from 'react';
import {shallow} from 'enzyme';
import ProjectStore from '../projectStore.js';
describe('<ProjectStore />', () => {
it('should return loading count', () => {
const ProjectStore = shallow(<ProjectStore />);
ProjectStore.setLodingCount(2);
expect(ProjectStore.lodingCount).toEqual(2);
});
});
but when I executed npm test it returned:
ReferenceError: ProjectStore is not defined
What am I doing wrong here?
When testing a static method from a class, you don't need to render that component. All you need to do is calling that static method from that class like the following:
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import ProjectStore from './projectStore.js';
describe('<ProjectStore />', () => {
it('should return loading count', () => {
ProjectStore.setLodingCount(2);
expect(ProjectStore.lodingCount).toEqual(2);
});
});
You can learn more from this answer.

When should I write {} surround a imported thing?

Please take a look at these:
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
As you see, it imports something, but why React is out of {} and all others are into it? {Component} { AppRegistry, Text, View }
Anyway, when should I wrap something into {}?
The difference is in how the file exports, without {} is the default export. There can only ever be one default export.
Anything inside the {} is part of a named exported function, class, or variable that is exported.
If you look at the react source code you will find the following es5 code.
var ReactComponent = require('./ReactComponent');
...
var React = {
...
Component: ReactComponent,
...
}
module.exports = React;
When you import React, { Component } you are importing all of React
along with React.Component as Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Becomes
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
This is commonly used to destructure an object like the following.
const person = {
firstName: 'John',
lastName: 'Doe',
};
const { firstName } = person;
Which is the same as
person.firstName
When you
export default MyComponent // import MyComponent
export MyComponent // import { MyComponent }

Flux threw Dispatcher is not a constructor

I try to use jspm with reactjs. I worked fine. But when I integrated it with flux package from npm. Then it always threw Dispatcher is not a constructor error.
My code as below
AppDispatcher.js
import Flux from 'flux';
export default new Flux.Dispatcher();
StoreBase.js
'use strict';
import {EventEmitter} from 'events';
import AppDispatcher from '../dispatchers/AppDispatcher';
const CHANGE_EVENT = 'change';
export default class BaseStore extends EventEmitter {
constructor() {
super();
}
subscribe(actionSubscribe) {
this._dispatchToken = AppDispatcher.register(actionSubscribe());
}
get dispatchToken() {
return this._dispatchToken;
}
emitChange() {
this.emit(CHANGE_EVENT);
}
addChangeListener(cb) {
this.on(CHANGE_EVENT, cb)
}
removeChangeListener(cb) {
this.removeListener(CHANGE_EVENT, cb);
}
}
I used reactjs#0.13.3, react-router#0.13.3 and flux#2.0.3. Could anyone help me on this?
If you are using Babel you can use below
import { Dispatcher } from 'flux';
const dispatcher = new Dispatcher();
export default dispatcher;
You should export the Dispatcher as follows
import Flux from 'flux';
export default new Flux.Dispatcher;

Categories