destructuring from module imports - javascript

I have a index.js in a folder called "vuex" with the following
const module = { state, mutations, actions, getters }
export default { module, plugin }
state, mutations, actions were imported from another file
I'm trying to get the "state" property in another file so I
import module from './veux'
then
const { state } = module
however state is undefined which is weird because console.log(module) shows me that module.state is present
I'm new to this ES6-7 flow so but what exactly am I doing wrong here?

Since you have exported the object {module, plugin} as default export
after importing like
import module from './veux'
module will have structure like
module = {
module: { state, mutations, actions, getters },
plugin
}
so in order to access state, you will write module.module.state or
const {module: {state}} = module; // nested destructuring
console.log(state)
an easier to understand and readable method would be to export your module with named export like
export const module = { state, mutations, actions, getters }
export default plugin
and import it like
import plugin, { module } from './veux'
after which you can do
const { state } = module;

I'm trying to get the "state" property in another file so I
import module from './veux'
const { state } = module
however state is undefined which is weird because console.log(module)
shows me that module.state is present
No, you're importing the whole default-exported object (with its module and plugin properties) as module. The property would be module.module.state.
I have a index.js in a folder called "vuex" with the following
const module = { state, mutations, actions, getters }
export default { module, plugin }
Don't. Use named exports for exporting multiple things:
export const module = { state, mutations, actions, getters }
export { plugin }
then you can do
import { module } from './veux'
const { state } = module

It'll work if you do this:
import { module } from './veux';

Related

Using vue.use in a library own

I'm using the vue-sfc-rollup lib to create a lib for Vue, so far it's ok, my lib is working, and I can use it in other projects, however, a doubt has arisen.
In which file could I add in my lib the use of bootstrap? to understand better I'm putting below the structure that the SFC generated for me..
The file entry.js
// iife/cjs usage extends esm default export - so import it all
import plugin, * as components from '#/entry.esm';
// Attach named exports directly to plugin. IIFE/CJS will
// only expose one global var, with component exports exposed as properties of
// that global var (eg. plugin.component)
Object.entries(components).forEach(([componentName, component]) => {
if (componentName !== 'default') {
plugin[componentName] = component;
}
});
export default plugin;
the file entry.esm.js
// Import vue components
import * as components from '#/lib-components/index';
// install function executed by Vue.use()
const install = function installZicketVueCheckout(Vue) {
Object.entries(components).forEach(([componentName, component]) => {
Vue.component(componentName, component);
});
};
// Create module definition for Vue.use()
export default install;
// To allow individual component use, export components
// each can be registered via Vue.component()
export * from '#/lib-components/index';

How to import external module in vue?

My code below is working fine:
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/auth';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
user
}
});
Is there a shorter way to import a module instead of writing the statement at the top? I instead write it directly inside the modules like below:
export default new Vuex.Store({
modules: {
user: import('./modules/auth'),
}
});
But unfortunately it didn't work (the external module was not imported successfully).
Import with braces is different from import without braces - the latter imports the module statically (at compile time) while the former imports the module dynamically (at run time) and is not an ES6 feature but something specific to Webpack.
You can read more in the Webpack documentation but the most important thing is that dynamic imports (those with braces) return a Promise instead of module reference. The module reference will be available when the Promise resolves. You can read more about lazy-loading Vuex modules in this article https://itnext.io/vue-js-app-performance-optimization-part-3-lazy-loading-vuex-modules-ed67cf555976
Before beginning, I'm using Vue 3 + Vuex 4.
In the file path/to/store/index.js that hold the Vuex store I used the code like this.
// path/to/store/index.js
import { createStore } from 'vuex';
import moduleA from './modules/moduleA';
import moduleB from './modules/moduleB';
export default createStore({
state: {},
mutations: {},
getters: {},
actions: {},
modules: {
moduleA,
moduleB,
},
});
And I created a file for each module as this
// file for each module
export default {
state: { ... },
mutations: { ... },
getters: { ... },
actions: { ... },
modules: { ... },
};

How can I export multiple object instances in TypeScript?

I am building a library in TypeScript that is using a dependency injection system (inversifyJS) to construct itself and resolve dependencies internally.
The problem I have is - I want to expose multiple instances from the injection system to the consumers of the library.
Currently what I am trying to do is:
import kernel from "./src/inversify.config";
import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';
export { kernel.get<EntityManager>(EntityManager) as EntityManagerInstance };
export { kernel.get<EntityManager>(LanguageService) as LanguageServiceInstance };
export { kernel.get<EntityManager>(StorageService) as StorageServiceInstance };
A solution that I see is possible is to use a facade to export types and access them later:
import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';
import InjectionFacade from './utils/injection.facede';
export { EntityManager, LanguageService, StorageService, InjectiorFacade };
// Usage:
// import {InjectionFacade, StorageService} from 'entity-manager';
// let injectionFacade: InjectionFacade = InjectionFacade.createAndResolve();
// let storageService: StorageService = injectionFacade.getStorageService();
But the problem with this is I have one more useless abstraction
Is there a way to implement this kind of solution without loosing type definitions and exporting ready-to-use objects?
You'd want to use a multiple-declaration variable, e.g.
export const
EntityManagerInstance = kernel.get<EntityManager>(EntityManager),
LanguageServiceInstance = kernel.get<EntityManager>(LanguageService),
StorageServiceInstance = kernel.get<EntityManager>(StorageService);

what is the difference between import Task and import { Task } in es6

What is the difference between
import { Tasks } from '../api/tasks.js';
and
import Task from './Task.jsx';
when to use {} and when to not use {} ?
(by the way, this is from meteor tutorial https://www.meteor.com/tutorials/react/update-and-remove)
You don't have to use the {} when you precise that it's a default export.
For example :
export default class Test{}
You can do :
import Test from './test'
In the other hand, if you don't precise "default" keyword, you have to precise {} :
export class Test {}
gives
import { Test } from './test'
when you do
import { Tasks } from '../api/tasks.js';
you are importing Task module from '../api/tasks.js';
when you do
import Tasks from '../api/tasks.js';
you are importing default export module from '../api/tasks.js'; Here Task is a variable which is referring default export module.
Example.
task.js
export default Task;
case 1: It is Task from task.js
case 2: It is Task variable pointing to Task module in task.js that is Task
if I do
import someVariable from './api/task.js' still it will work because someVarible will point to default export module that is Task module in task.js
If I do
import {someVariable} from './api/task.js' it will search for module someVariable in task.js but it is not there so now it is undefined.
if you want to grab the all modules you can do
import * as test from "Test";
If you exporting only some modules and not all then you have to specify wictch module you want
import { Module1, Module2, Module3 } from "Modules"; //grab only given in {}
if you have only export default Test you can to
import "Test";
read more about modules

How to use React.js to render server-side template on Sails.js?

I am trying to build an isomorphing app with Sails.js and React. Client-side part is easy. But I run into problems with server-side rendering.
When I try to server-render an *.jsx file with React, I got this:
renderToString(): You must pass a valid ReactElement
I am using sailsjs, react and sails-hook-babel (for ES6 syntax).
./assets/components/Auth.jsx:
import React from 'react';
export class Auth extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='auth'>
Very simple element without any logic just for test server-rendering.
</div>
);
}
}
./api/controllers/AuthController.js:
var Auth = require('./../../assets/components/Auth.jsx');
import React from 'react';
module.exports = {
render: function (req, res) {
//var markup = React.renderToString(
// Auth
//); // This throws an error
console.log(Auth); // {__esModule: true, Auth: [Function: Auth]}
//res.view("layout", {app: markup});
}
};
I have tried both ES5/ES6 syntax everywhere. Error occurs everytime. At clientside this Auth.jsx works fine (I am using webpack with babel-loader).
Your problem isn't with your component itself, it's how you're exporting it from your module.
When using just export you need to import your module like this.
import {Auth} from 'auth';
Just using export allows for exporting more than 1 thing from your module.
// My Module.
export function a(x) {
console.log('a');
}
export function b(x, y) {
console.log('b');
}
import { a, b } from 'myModule';
or you can use import * from 'myModule';
This is called a named export.
What your use case begs for is the use of export default which allows a single object to be exported from your module.
export default class Auth extends React.Component {}
Thus letting you import your module as a single object without curly braces.
import Auth from 'auth';
Then you need to render using either use JSX syntax React.renderToString(<Auth />); or
React.createElement(Auth);
You can read all on how modules in ECMA Script 6 works here

Categories