ECMAScript import { } from './somwhere.js' - javascript

I'm trying to fully understand JavaScript import and exports. According to the syntax diagram on https://tc39.es/ecma262/#sec-exports it's valid to have an empty block which I assume means import nothing so what is it for? Example:
import { } from './somewhere.js'

It will run the code in somewhere.js. That might be useful for initializing something, but if that's all you need, you can get the same effect with:
import './somewhere.js'
So i don't really see a reason to write the example you're asking about.
If i had to guess, i'd assume the reason it's allowed is that a definition allowing N named imports (eg, import { foo, bar, baz } from './somewhere.js") would very easily have a base case of import { } from './somewhere.js, and there just wasn't a reason to ban the empty case.

Let's take code bellow as our example
./somewhere.js
console.log('imported');
export const PI = 3;
Importing code above using import { } from './somewhere.js' will result in logging into console. The same would be true for import './somewhere.js'.

Related

How_To_Solve_ReactJS_Problem

Sorry for my bad english and a new learner programming.
I have a single problem with React.JS in App.js,
I have written an exterrnal JS file, called Fundamental.js, the code is the following:
const testing = () => {
console.log('test log 12456');
}
export default testing;
When I import Fundamental.js file into App.js, my VS Code shows a popup message:
'testing' is defined but never used.
how to solve it?
the import list in my React App.js is:
import logo from './Linux_Logo.png';
import './App.css';
import testing from './FundaMental';
Thank you so much to whoever solves my problem!
Welcome to SOF. In your component testing should be Testing [capitalized] and In testing nothing is returned that's why showing this in the terminal. Try this plz:
import React from 'react';
function Testing() {
return (
console.log('test log 12456');
)
}
export default Testing
when importing:
import Testing from './FundaMental';
It is better to keep the same name of the function name and the js file name.
VS Code is saying that you imported a function but you're not using it.
Your testing module defines the function testing. It doesn't execute it.
There are two ways to get rid of the warning:
Call the testing function in App.js, or
Don't import it into App.js.
If testing is the beginning of a React component then follow #Pabel Mahbub's answer, including the suggestion to rename the function Testing and rename the file Testing.js. As your app grows that will make it easier to manage.
This is only a warning/reminder that you import something but you never used it. React has this kind of checking that will warn us of the unusual code that we have. To fix this warning either trigger the function or remove it. Hope this helps!

Difference between import * as & import { default as }

I have the following imports:
import { default as service } from "../service";
VS
import * as service from "../service";
My service is exported like so
module.exports = {
init(store) {
_store = store;
},
beginPayment() {
}
};
I would expect that only the second import would work since there is no export default, however both seem to work.
What is the difference between these? Is one preferred over the other?
If this is a duplicate I apologize, I didn't find anything specific to my example on SO or Google.
If you are importing the default, there has to be a default.
In general, the community appears wary of default exports at the moment as they seem to be less discoverable (I have no specific citation, but I've watched the conversation!)
If you are working in a team, whatever they say is the correct answer, of course!
So without a default, you need to use:
import * as service from "../service";
Or choose a specific thing:
import { specificNamedThing } from "../service";

es6 how to import already defined in another js package

I have a package that I use somewhat like this:
import { something } from 'somewhere';
But then I have another package that I import, and I need to define the same something name which is defined in it.
import myConsts from 'SomewhereElse';
const { something, another } = myConsts;
I get an eslint error (and rightly so) something already defined.
Here's a real example:
import { connect } from 'react-redux';
// following lines from react-native-kontaktio sample code...
import Kontakt from 'react-native-kontaktio';
const { connect, configure, startScanning } = Kontakt;
I tried
import { connect as kontaktConnect, configure, startScanning } from 'react-native-kontaktio'
but get Possible promise rejection ... (reactNativeKontaktio.connect) is not a function.
If I try to change the
import { connect as reduxConnect } from 'react-redux';
I'll have to change the export as follows. Won't that break my code elsewhere?
// export default connect(mapStateToProps, mapDispatchToProps)(AppMain);
export default reduxConnect(mapStateToProps, mapDispatchToProps)(AppMain);
How can I overcome this? Can I ignore the warning in some cases? There is no Polymorphism in Ecma6 right?
This is NOT a question about two classes with the same name, but about two classes with a method or a constant of the same name.
The answer there seems to be applicable here, to use:
// instead of: import myConsts from 'SomewhereElse';
import { something as somethingElse, another } from 'SomewhereElse';
But then, when I use... somethingElse().then(()=> ... I get an error Possible promise rejection ... (SomewhereElse.something) is not a function
This also is NOT a [question about fixing the general is already defined eslint error] (Javascript standardjs - how to fix 'is already defined'?), since I am not talking about writing MY code, but rather how to import and use someone else's two packages when they have this clash problem.
No I think you can't ignore the warning, because 2 variables with the same name are present in the same scope.
You may need to import in this way:
import { connect as somethingElse} from 'react-redux';
To avoid to variables with the same name.
I hope it will help you

Should I use both `import 'rxjs/Rx'` and `import { Observable } from '#rxjs/Observable'`

import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import { Observable } from '#rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/observable/throw';
#Component({});
export shellModule{}
This is a piece of code form my Angular app that I copied from somewhere (I have removed the definitions in the exported module. I am using it to make a service to call APIs.
In the imports in this particular file, why is it that Observable is imported separately even though the entire rxjshas been imported. If a particular module is being imported in its entirety, why is a particular object from it imported separately? I tried asking this question at the forum from where I took it, but there was no answer. I want to understand if this somehow helps with optimization of code.
In general:
In Typescript, the way modules are handled would require you to either load in the entire library with the import * as rx from 'rxjs/Rx', or a specific exported module within the library to use it, so the the compiler loads in the types.
Reducing your imports to only the specific modules you need sets up your app to use tree shaking from Angular's AOT compilation. This is not done by the typescript compiler, but by a tool called rollup. So, it can help with optimizing code later, but it doesn't automatically do so.
As far as compilation overhead, bringing in the whole library might slow down the compiler a bit... but this isn't a very strong point except for massively complex libraries.
I, personally, prefer importing in specific modules because it makes the calling code a little cleaner since I don't need to use that global name to get to the specific name. rx.Observable vs Observable. A good example of this is the lodash library (rxjs is a bit more complex...)
Honestly, importing entire libraries like the line you have there: import 'rxjs/Rx' doesn't make sense to me. You should only import specific exported modules. Try removing it, seeing what errors you get, and then using the * as rx syntax instead.
As far as rxjs goes - it is a little wonky when you want to import specific operators like this question does - so the way to get specific operators is with: import 'rxjs/add/observable/from' - but that also requires a tinkering with your webpack set up as outlined in the referenced question's answer.
Let's see what the rxjs/Rx module exports:
export { Subject, AnonymousSubject } from './Subject';
export { Observable } from './Observable';
export { Operator } from './Operator';
export { Observer } from './Observer';
export { Subscription } from './Subscription';
export { Subscriber } from './Subscriber';
export { AsyncSubject } from './AsyncSubject';
export { ReplaySubject } from './ReplaySubject';
export { BehaviorSubject } from './BehaviorSubject';
...
import './add/observable/bindCallback';
import './add/observable/bindNodeCallback';
import './add/observable/combineLatest';
...
So it exports RxJs classes and also imports operators from the add folder. So as you can see it loads everything in the library. It doesn't export any global object though. So you need to use named export like this:
import * as Rx from 'rxjs/Rx'
to be able to use an exported class:
Rx.Observable.of(12, 3);
This emulates what you would have if you loaded the library using the bundle - a global Rx object:
<script src="rxjs/bundles/Rx.js">
If you want to use Observable without Rx global object, you need to import it separately:
import { Observable } from '#rxjs/Observable';
Observable.of(1);
Importing both
import { Observable } from '#rxjs/Observable';
import 'rxjs/Rx';
is not a good practice, but may be used if you don't want to import every operator separately.
Also see How to correctly import operators from the rxjs package.

In VSCode when exporting functions: "Individual declarations must be all exported or all local"

I recently upgraded to Visual Studio Code 0.5.0 and some new errors cropped up that weren't there before.
I have a bunch of functions that are declared locally and then exported. Since the upgrade, however, hovering over each of the local function names produces the error Individual declarations in merged declaration functionName must be all exported or all local.
This is an example local function that is exported.
var testParamsCreatorUpdater = function (lTestParams, creatorID){
lTestParams.creator = creatorID;
return lTestParams;
};
module.exports.testParamsCreatorUpdater = testParamsCreatorUpdater;
I realize I can change this to...
module.exports.testParamsCreatorUpdater = function (lTestParams, creatorID){
lTestParams.creator = creatorID;
return lTestParams;
};
And prepend module.exports. to every testParamsCreatorUpdater() call.
But why is the first snippet wrong? As I understand it, require() makes everything in the module.exports object available to whatever required it.
I had this issue in Webstorm , I Restarted it and it went away
I think at a JavaScript level it cannot differentiate between:
var testParamsCreatorUpdater = ...
and
module.exports.testParamsCreatorUpdater = ...
as the names are the same. I got the exact same error (leading me to this post) in TypeScript when I tried this:
import { AuditService } from '../services/audit.service';
import { Audit } from '../models/audit.model';
#Component({
selector: 'audit',
templateUrl: './audit.component.html',
})
export class Audit {
constructor(private auditService: AuditService) {
}
}
So TypeScript did not like that I imported a module called Audit and exported a class also called Audit.
You are exporting a variable in this file which is imported in the same file module (locally).
I think it's related to the feature of merged declaration for TypeScript ref. I have not done the detailed research for Typescript but it seems that it can include Javascript in the Typescript file.
I guess the way testParamsCreatorUpdater was declared in the Javascript was detected to be error by VSCode because it thinks the two declarations cannot be merged.
So DuckDuckGo got me here searching for the exact same error, but in 2022. I didn't find the exact reason so posting as an update and for completeness.
import { Something, SomethingElse } from './some/path';
import { ref } from 'vue';
// Many lines of code
function doTheStuff() {
// The declarations were previously just local variables ...
// const Something = ref<Something>();
// const SomethingElse = ref<SomethingElse>();
}
// ... but then I decided to export them and got the error
export const Something = ref<Something>();
export const SomethingElse = ref<SomethingElse>();
You simply can not import Something as a type and then export Something variable as a value of a kind (here a vue reference object). However, you can name a local variable the same name as the type, like I originally had. It is the import/export combination where things got broken. Solution for me was to locally rename the types:
import {
Something as SomethingType,
SomethingElse as SomethingElseType
} from './some/path';
import { ref } from 'vue';
// ...
// No naming conflict anymore
export const Something = ref<SomethingType>();
export const SomethingElse = ref<SomethingElseType>();

Categories

Resources