All:
I am pretty new to ES6, when I study ES6 module with this post:
http://www.2ality.com/2014/09/es6-modules-final.html
[1]
there is one line:
export { each as forEach };
I wonder if anyone could tell where can I find the usage intro to this specific syntax (especially the curly bracket and AS )
[2]
Another confuse is about default export:
cmod.js
export default var Obj={};
Obj.hello = function(){
return "hello";
}
main.js
import hello from "./cmod"
console.log(hello.hello());
I wonder why I got error like: :
SyntaxError: cmod.js: Unexpected token (1:15)
> 1 | export default var Obj={};
| ^
But if I move the declaration to a separated line like:
var Obj = {}
export default Obj;
Obj.hello = function(){
return "hello";
}
Then everything works, why I can not declare a variable and export it?
Thanks
[1] export { each as forEach }; this line means, you can export one or more items as objects with or without alias names.
example-1:
const MY_CONST = ...;
function myFunc() {
...
}
export { MY_CONST, myFunc };
example-2:
export { MY_CONST as THE_CONST, myFunc as theFunc };
Related
I am trying out a small sample in nextjs. All that the proj does is to fetch json data from a file and try displaying it in list of a component. But the behavior is weird. Its getting into infinite loop and I have no clue what's wrong. Could some one take a look at https://github.com/SamplesForMurthy/sampleCode and help me figure out what the issue is? Not able to fetch the data nor I am able to display.
I cloned and fixed. You don't need to use fs.readFileSync here, or fs at all for that matter. You can simply import the .json file as an arbitrarily named variable then map it out.
Here is how I got the data rendering:
import React from 'react';
import testData from '../TestData/SampleData.json';
import SampleParentComponent from '../components/SampleParentComponent';
function TestPage({ filecontent }) {
console.log(`filecontent: ${filecontent}`);
return (
<div>
<SampleParentComponent data={filecontent}></SampleParentComponent>
</div>
);
}
export const getStaticProps = async ctx => {
console.log(ctx.query);
const filecontent = await testData;
return {
props: { filecontent }
};
};
export default TestPage;
/**
* (property) filecontent: {
data: {
seqNo: number;
contactName: string;
}[];
}
*/
I've been making a discord.js bot following the official guide.
I have all my commands in the /commands folder as advised.
Then I followed the course to create a currency system with sequelize, following this page from the same guide.
I have a balance.js file inside the commands folder, but when I'm calling it, it gives me this error:
TypeError: currency.getBalance is not a function
I've defined the function in my app.js file, but how can I export it (or use it) inside the balance.js which is called by the app.js file?
This is the function defined in the main file app.js:
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
This is balance.js:
module.exports = {
name: 'balance',
description: 'Informs you about your balance.',
cooldown : 10,
guildOnly : true,
aliases: ['bal', 'cur', 'gem', 'gems'],
execute(message, args) {
const Discord = require('discord.js');
const { Users, CurrencyShop, UserItems, CardBase, UserCollec } = require('../dbObjects');
const currency = require('../app.js')
async () => { const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
UserCollec.sync(); }
const target = message.author;
return message.channel.send(`${target} has ${currency.getBalance(target.id)}<:Gem:756059891465977886>`);
},
};
EDIT:
I progressed. Now I understand that I have to import the currency variable, which has been declared as a new Discord.Collection() in app.js.
I need to refer to this variable in a module and this module doesn't seem to see it as a collection. How do I import it?
I want to access json with a value in input.
My function and json
import pet3 from '../../utils/pet3' //my json file
const getValueFromJson = (value) => {
const data = pet3
console.log(data.components) //it works fine
console.log(data.value) // it is undefined
}
getValueFromJson("components")
You can access the object keys dynamically by using the square brackets:
import pet3 from "../../utils/pet3"; //my json file
const getValueFromJson = (value) => {
const data = pet3;
console.log(data[value]);
};
getValueFromJson("components");
Edit:
Alternately, you can install and use a 3rd party library like lodash which provides the _.get() method that can be used like this:
import get from "lodash/get"; // if not installed, run `npm install lodash --save-dev`
const getValueFromJson = (value) => {
const data = pet3;
console.log(get(data, value, "default value")); /* returns "default value" if key is undefined. */
};
getValueFromJson("components.filename");
For example.
We have a couple of ES6 module imports, say:
import Module1 from './module_1';
import Module2 from './module_2';
Am using Babel to transpile ES6 into ES5
Have another function, which given a string, returns a reference to the imported ES6 module:
getModule(name) {
switch(name) {
case "Module 1":
return Module1;
case "Module 2":
return Module2;
default:
return null;
}
}
The naming convention is pretty straight forward and consistent
So how to remove the manual switch statement ?
Initially I thought, we can get away with using eval. something like:
getModule(name) {
// removes spaces. so "Module 1" to "Module1"
const ref = name.replace(/\s+/g, "");
return eval(ref);
}
But Babel changes the variable names etc
and has pulled the carpet from under my feet.
Just to demonstrate a non-transpiled example works with:
var foo = function() { console.log("called foo") }
var bar = function() { console.log("called bar") }
eval("foo")() // logs "called foo"
eval("nope") // throws ReferenceError: Can't find variable: nope
Is it possible to get a hash of imports in a file, called say localImports ?
so that we can write:
getModule(name) {
// removes spaces. so "Module 1" to "Module1"
const ref = name.replace(/\s+/g, "");
return localImports[ref];
}
How to implement such a function using ES6 and Babel ?
Also as a bonus, is it possible without using eval ?
This worked for me:
Import the modules.
import Module1 from './module_1';
import Module2 from './module_2';
Cache the modules in local scope with whatever name you want. In this case I use the same name: Module1, Module2.
setModules(){
this.Module1 = Module1;
this.Module2 = Module2;
}
Get the reference to the module using a reference made in local scope.
getModule(name) {
return this[name]; //e.g. name = 'Module1'
}
If you're compiling the imports to require using Babel, you could just use require directly and make a map:
const modules = {
'Module 1': require('./module_1'),
'Module 2': require('./module_2')
};
function getModule(name) {
return modules[name];
}
I have a Component that has an injected service, which makes an Ajax call. I can receive the JSON data successfully and can dump it into the console after the promise "THEN" returns.
Here's my component. I can see the dumped data, but how do I set the component properties with that JSON and have it accessible in the template? Also, why can't I use "this.get" in my function below?
import Ember from 'ember';
export default Ember.Component.extend({
attr_types: Ember.inject.service('svc-attrtypes'),
atype_list: [],
actions: {
getATypes: function() {
this.get('attr_types').getTypes().then(function(json){
console.log(json);
this.atype_list = json;
console.log(this.atype_list);
// below returns: TypeError: this.get is not a function
this.get('atype_list').pushObjects(json);
});
}
}
});
In my template I have this:
{{#each atype_list.alltypes as |a|}}
<li>{{a.attr_type}} - {{a.attr_type_desc}}</li>
{{/each}}
If I manually place my JSON into the atype_list it shows perfectly on the template. But if I try to set it after my Ajax returns, nothing shows, except for in the console output.
I appreciate any help. I am sure I a missing something simple. ( or more likely, I'm just going about this all wrong)
This changed with anonymous function passed to then. You have to save this or use es6 arrow function syntax.
import Ember from 'ember';
const { service } = Ember.inject;
export default Ember.Component.extend({
attrTypes: service('svc-attrtypes'),
atypeList: [],
actions: {
// es6 version
getATypes(){
this.get('attrTypes').getTypes().then(array => {
this.set('atypeList', array); //replaces original array
this.get('atypeList').pushObjects(array); // adds array's elements to the end
});
}
// es5 version
getATypes: function () {
var _this = this;
this.get('attrTypes').getTypes().then(function(array){
_this.set('atypeList', array);
}
}
}
});
You wrote that you are new to ember, so I added little more syntax sugar. Also check ember-cli if you don't know about that already.