I'd like to import specific functions from another module. But I faced naming collision: I have similar function names in my importing file. I'd like to do something like this:
// exporterFile.js
export {
set,
get,
has,
foo,
bar,
}
// implementation code for set, get, etc.
// importerFile.js
import {get, set} as exporter from "exporterFile.js"
function get() {
// some code and call set from exporter
exporter.set(something)
}
I know I could import * as exporter from "exporterFile.js" but it lacks readability and does not show what methods (functions) I am using from the exporter file.
Also, I know I could import {get as exporterGet, set as exporterSet} from "exporterFile.js" but it is not so readable.
Is there an elegant, clear, readable way to import selected functions from a module without naming collision? If not, what is the best practice and approach and suggestion: readability is very important, tree-shaking is a consideration as well.
There are no alternatives to the two ways you already mentioned. Readability is subjective, but both exporterGet() and exporter.get() are good choices that are common. If you explicitly want to list all the used function in the import statement itself, you will have to give them individual aliases. Tree shaking tools will be able to handle both formats.
Related
I've just finished writing a big quickbooks wrapper in JavaScript with a lot of parts in different files, e.g. a file for tax, a file for accounts, a file for auth, etc. I'd like to make it so that developers using this wrapper will only have to do one import that will contain all the functions I've written.
Hierarchy is something like this:
QbTax.js
QbAccounts.js
QbAuth.js
I'd like to have another file, or a way that a developer using this wrapper would only have to import one thing, then be able to call all functions from the above files from that one import.
Something like this:
import * as qb from './unifiedQbFile.js';
qb.thisIsATaxFunc();
qb.thisIsAnAccountsFunc();
qb.thisIsAnAuthFunc();
What is the best way to approach this?
The only idea I have at the moment is to write prototypes in a file (unifiedQbFile.js for instance) and export those. I'd import all the functions from my other files in that unified file then call them in my new prototypes. That seems messy though.
you can have one index.js file that exports all files then you can import that index.js file. I would personally go with this method.
// index.js
export { qbTaxFunc } from 'QBTax';
export { qbAccountsFunc } from 'QbAccounts';
export { qbAuthFunc } from 'QbAuth';
Now in some other script to import it you can do.
import qb from 'path-to-index.js';
// All functions should now be available
qb.qbTaxFunc();
qb.qbAccountsFunc();
qb.qbAuthFunc();
Is it possible to import named exports dynamically?
I have a file, banana.js with hundreds of named exports. Id like to import them on demand. Is this possible? And if it is, will it only load that export and not all?
I know its possible to import them dynamically from individual files but I want them in the same file.
Example below..
// banana.js
export const banana_1 = {
..
}
export const banana_2 = {
..
}
// main.js
const currentPage = 1
async getSomething(){
let { `banana_${currentPage}` } = await import('./banana.js');
const foo = `banana_${currentPage}`
}
Fyi im using Vue.js
From what I know, you might have to use require('./banana.js') here. Please note that require is synchronous, so need for await. If you use eslint and it forbids usage of require, just add // eslint-disable-line to the end of that line. BTW, I don't know Vue at all.
About the object you import, you should probably make an array instead of suffixing each export with a number.
Edit: I just realized that dynamic imports are a thing not only possible with require, so ignore the first paragraph.
Based on your response to my question I offer the following solution. I understand not wanting to deploy and use a full database solution for the sake of hot loading some JSON objects. I'm unsure of your use case and other details related to your project.
You can use a self contained database like SQLite. Instead of setting up a NoSQL or SQL server. You can instead just store what you need to the SQLite file. Since Vue requires Node.js you can use the Node.js SQLite3 library https://www.npmjs.com/package/sqlite3.
I hope this helps.
I'm learning Javascript ES6 on codecademy and there´s a lesson about named exports and export as statement. For example:
export { specialty as chefsSpecial, isVegetarian as isVeg};
My question is about what are the benefits of using export as rather than named exports like:
export let specialty = '';
or
export { specialty, isVegetarian };
So far my thought is that export as could be used for variable names standarization in projects, but haven´t come up with further advantages on makeing use of it.
also, do developers make use of this export as functionality? I´ve tried to get answers on the web but everything that's about exports and imports doesn't mention anything about export as .
Using as just allows you to define the symbol name of the export if you want it to be different than the name is locally.
So your publicly exported symbol name can be something different than you use locally.
My question is about what are the benefits of using export as rather than named exports like:
There's no particular benefit if you're happy with the internal name being the same as the exported name. If you want a different exported name, you can either rename everything locally to the new name or use export as to change just the name of the exported symbol.
So far my thought is that export as could be used for variable names standarization in projects, but haven´t come up with further advantages on makeing use of it.
I could imagine it being convenient to centralize the definition of the exported symbols in one place without forcing the definition of the functions themselves to be all in one place. If you were designing the code originally to be exported and publicly reusable, then you'd probably just name things from the beginning with an appropriate exported name and not use export as. But, if you had a body of existing code that you were now trying to put a wrapper around and for various reasons you didn't want to rename a lot of things internally, I could see some convenience to using export as.
Keep in mind that it's just a syntactical convenience. These two scenarios are functionally equivalent:
function sayGreeting() {
console.log("hi");
}
const greet = sayGreeting;
export greet;
And this:
function sayGreeting() {
console.log("hi");
}
export {sayGreeting as greet};
Or, of course you could have just written it like this in the first place:
export function greet() {
console.log("hi");
}
Personally, I agree with Geuis that import as is more useful than export as and the canonical use for import as is when you're importing two modules that both define the same symbol name (a name collision which can happen in the real world), then you can use import as to change the local symbol name to something that does not conflict with the other module you are importing.
This is the best reference article I've found on import and export syntax:
ECMAScript 6 modules: the final syntax
In learning more about ES6/2015 imports, I've come across a couple of cases where I'd like to change the namespace of the default member in the import scope.
Basically the equivalent of import {myMember as name} from 'my-module', but for the default member. I expected something like import defaultMember, {defaultMember as name} from 'my-module', but that seems not to work.
It seems like this should possible:
Mozilla Docs
It is also possible to use the default syntax with the ones seen above (namespace imports or named imports). In such cases, the default import will have to be declared first...
Perhaps not the actual answer, but a solution that I'm using.
For this example, I was using Node-Simple-Schema, and did not want to track imports of it as it is often used across the global scope on the project I'm working on.
The problem is that when import SimplSchema from "simpl-schema'; is used, then "SimpleSchema" as a convention is not available globally.
So I created a code file "SS2.js" and placed the following in it:
import SimpleSchema from 'simpl-schema';
var SS2 = SimpleSchema;
export {SS2};
Then in the working file, I do a subsequent "chained" import and with the following:
import {SS2} from './imports/SS2.js';
SimpleSchema = SS2;
This gives me the default module export convention "SimpleSchema" available globally once again.
I read somewhere (forgot the source, unfortunately), that it's more efficient somehow to do this:
import _find from 'lodash/find';
as opposed to:
import _ from 'lodash'; // just to use _.find
I understand how it could be more efficient to import a single function, but where is the efficiency/performance gain exactly? Is it webpack-related? If I'm not using webpack as my build engine, does it matter?
When you import a big library, you import the whole thing (at least with most bundlers), since there is no clear way to distinguish what is necessary from the object you imported.
I'm not too familiar with lodash but it's entry point should look something like this:
module.exports = {
find: require('./find.js')
filter: require('./filter.js')
// rest of the exposed functions
}
With the second import style you got this whole object, but you only need 1 function from all of this.
So if you do this:
import _ from 'lodash'
You will end up with the whole lodash library packed into your bundle, while if you do this:
import find from 'lodash/find'
You will only have find and it's dependencies, resulting in a considerably smaller bundle size.