Importing / exporting Javascript Object Properties - javascript

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.

Related

How to programmatical import module to local scope of nodejs?

The code environment is browser. bundle tool is webpack. I have a router.js file like:
import foo from './views/foo.vue'
import bar from './views/bar.vue'
import zoo from './views/zoo.vue'
//use foo, bar, zoo variables
I've many '.vue' files to import like this under views folder. Is there a programmatical way to auto import all [name].vue as local variable [name]? So when I add or remove a vue file in views, I don't need to manually edit router.js file. this one seems a little dirty.
for (let name of ['foo', 'bar', 'zoo']) {
global[name] = require(`./views/${name}.vue`)
}
Nope, that's it. You have a choice between dynamic import and automation, or explicit coding and type-checking / linting.
Unfortunately, it's one or the other. The only other way to do it is meta-programming, where you write code to write your code.
So you generate the import statements in a loop like that, and write the string into the source file, and use delimiting comment blocks in the source file to identify and update it.
The following works for me with webpack and vue.
I actually use it for vuex and namespaces. Hope it helps you as well.
// imports all .vue files from the views folder (first parameter is the path to your views)
const requireModule = require.context('./views', false, /\.vue$/);
// create empty modules object
const modules = {};
// travers through your imports
requireModule.keys().forEach(item => {
// replace extension with nothing
const moduleName = item.replace(/(\.\/|\.vue)/g, '');
// add item to modules object
modules[moduleName] = requireModule(item).default;
});
//export modules object
export default modules;

Is there a way to lazy export file with ESModule?

I have a project which has many files to export. For now I use CommonJS to lazy export those files:
module.exports = {
get AccessibilityInfo() {
return require('../Components/AccessibilityInfo/AccessibilityInfo');
},
get ActivityIndicator() {
return require('../Components/ActivityIndicator/ActivityIndicator');
},
// .... many other files
}
ReactNative do the same thing React Native, so that a file is only loaded when it is imported specifically.
I want to refactor this file with ESModule, but I can't find a way to export files lazily.
Is there a way to export files lazily with ESModule?
Is it necessary to export files lazily with ESModule?
The ECMAScript way of doing this is via dynamic import(). The syntax is basically the same and it does what you'd expect, except that it returns a promise (which is great - it means that the operation does not lock the thread). Your code could e.g. look like this:
export const getAccessibilityInfo = () =>
import("../Components/AccessibilityInfo/AccessibilityInfo");
export const getActivityIndicator = () =>
import("../Components/ActivityIndicator/ActivityIndicator");
You would then grab these modules like this:
import { getActivityIndicator } from "./the/module/above";
const ActivityIndicatorPromise = getActivityIndicator();
// Whenever you need to use the ActivityIdicator module, you first need to await for the promise resolution
ActivityIndicatorPromise.then(ActivityIndicatorModule => {
// Do what you want here...
});
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports. It also lists the cases where this syntax would be preferable. If you were hoping that this was possible using the static import syntax (import X from '../whatever';), rest assured - it is not.
No, there is not way to lazy export in react native
export does not have an effect on performance
import/require files have to make part of JS Bundle
components which are alive in memory put an effect on performance
In my point, there are three-way to make good performace
Solution 1: Dynamic Import
but you can load only dynamically component like this
const allPaths = {
path1: require('file path1').default,
path2: require('file path2').default
};
const MyComponent = allPaths('path1')
allPaths('path1') in this case only path1 component will be active
_
Solution 2: Stop render further Tree of Component
stop render on specific condition so further tree should not be active in memory and give not any effect on performace
render() {
const {isReady} = this.state;
if(!isReady)
{
return null;
}
return (
<ActualComponent />
)
}
-
Solution 3:Stop extra rerendering
you can use shouldComponentUpdate to stop extra renrendring. component on specifc condition only
shouldComponentUpdate(nextProps, nextState) {
return this.state.name != nextState.name;
}

Import dynamically named exports

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.

ES6 Imports inside Export default

I'm currently migrating the whole code of a NodeJS application from ES5 to ES6/7.
I'm having trouble when it comes to imports :
First, I understood that making an import directly call the file. For example :
import moduleTest from './moduleTest';
This code will go into moduleTest.js and execute it.
So, the real question is about this code :
import mongoose from 'mongoose';
import autopopulate from 'mongoose-autopopulate';
import dp from 'mongoose-deep-populate';
import { someUtils } from '../utils';
const types = mongoose.Schema.Types;
const deepPopulate = dp(mongoose);
export default () => {
// DOES SOMETHING USING types AND deepPopulate
return someThing;
};
export const anotherModule = () => {
// ALSO USE types and deepPopulate
};
Is this a good practice to have types and deepPopulate declared outside of the two exports ? Or should I declare them in each export ?
The reason of this question is that I'm having a conflict due to this practice (to simplify, let's say that dp(mongoose) will call something that is not declared yet)
You can only have one 'default' export to a module, or you can have multiple 'named' exports per module. Take a look at the following for a good description of handling exports in ES6: ECMAScript 6 Modules: The Final Syntax

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