Export multiple modules ES6 - On import, all modules are within the first one I "peel off" - ecmascript-6

I am doing the following (both of the exported are objects):
SlateInfo.js
export default {SlateRules, SlateSchema};
and then in another file
import {SlateRules, SlateSchema} from 'SlateInfo';
But what I get is that SlateRules is defined as an object containing SlateRules and SlateSchema
SlateSchema is left undefined.
Where am I going wrong/what am I misunderstanding?

import {SlateRules, SlateSchema} from 'SlateInfo'; is for importing named exports. However, export default {SlateRules, SlateSchema}; is a default export, exporting an object with two properties.
If you want named exports then you need to omit the default:
export {SlateRules, SlateSchema};
Or use a default import and destructure the object:
import SlateInfo from 'SlateInfo';
const {SlateRules, SlateSchema} = SlateInfo;
When should I use curly braces for ES6 import? has a lot of examples showing how named and default exports work.

Related

Export and export default a variable

What's the right way to do something like this? My goal is to have my list of things I'm exporting not have to be duplicated. Right now I have to make two lists of exports, one for the export, and one for the default export.
const exports = {
Something,
SomethingElse
}
export exports
export default exports
My goal is to be able to import like this:
import everything from 'my_module'
or
import {Something} from 'my_module'
export exports is not valid syntax, it looks similar to something that TypeScript did support but that is deprecated in favour of modern syntax. Do not use it.
export default exports; and import everything from 'my_module'; would work together, but it's not recommended to default-export objects since it doesn't work with named imports.
Instead, use named exports:
export {
Something,
SomethingElse
}
(or put the export right on the declarations of Something and SomethingElse), then you can choose to do either
import {Something} from 'my_module';
or
import * as everything from 'my_module';

How to use SQLAlchemy Utils in a SQLAlchemy model

I'm trying to create a user model that uses UUID as primary key:
from src.db import db # SQLAlchemy instance
import sqlalchemy_utils
import uuid
class User(db.Model):
__tablename__ = 'user'
id = db.Column(sqlalchemy_utils.UUIDType(binary=True), primary_key=True, nullable=False)
But when I generate the migrations I receive:
File "/home/pc/Downloads/project/auth/venv/lib/python3.6/site-packages/alembic/runtime/environment.py", line 836, in run_migrations
self.get_context().run_migrations(**kw)
File "/home/pc/Downloads/project/auth/venv/lib/python3.6/site-packages/alembic/runtime/migration.py", line 330, in run_migrations
step.migration_fn(**kw)
File "/home/pc/Downloads/project/auth/migrations/versions/efae4166f832_.py", line 22, in upgrade
sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(length=16), nullable=False),
NameError: name 'sqlalchemy_utils' is not defined`
I had try to explicity inform the module I'm using like this and use a 'internal' implementation that SQLAlchemy
Obs: If I manualy import the sqlalchemy_utils in the /migrations/version/efae4166f832_.py and remove the length that is generated automaticaly sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(length=16), nullable=False) it works fine
I generate the migrations using a generate.py script:
from src import create_app
from src.db import db
from flask_migrate import Migrate
# Models
from src.user.models.user import User
app = create_app()
migrate = Migrate(app, db)`
Obs: MySQL engine
I expect that when I generate migration it generate a user model that uses UUID implemented from SQLAlchemy Utils as primary key
You have just to add:
import sqlalchemy_utils
to your script.py.mako inside migrations folder
Thanks, Marco, but I have already fixed it. I have put the import import sqlalchemy_utils inside env.py and script.py.mako, I have also put the following function:
def render_item(type_, obj, autogen_context):
"""Apply custom rendering for selected items"""
if type_ == "type" and isinstance(obj, sqlalchemy_utils.types.uuid.UUIDType):
# Add import for this type
autogen_context.imports.add("import sqlalchemy_utils")
autogen_context.imports.add("import uuid")
return "sqlalchemy_utils.types.uuid.UUIDType(), default=uuid.uuid4"
# Default rendering for other objects
return False
Inside the env.py, and at the same file I have set render_item=render_item in the function run_migrations_online:
context.configure(
...,
render_item=render_item,
...
)
I researched to do this automatically, but I couldn't find nothing that could help me.
The order of the operations matter:
export FLASK_APP=manage.py
flask db init
Do the tutorial above
flask db migrate
flask db upgrade
Background
It would be ideal if you didn't have to go and manually edit each migration file with an import sqlalchemy_utils statement.
Looking at the Alembic documentation, script.py.mako is "a Mako template file which is used to generate new migration scripts." Therefore, you'll need to re-generate your migration files, with Mako already importing sqlalchemy_utils as part of the migration file generation.
Fix
If possible, remove your old migrations (they're probably broken anyway), and add the import sqlalchemy_utils like so to your script.py.mako file:
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils #<-- line you add
${imports if imports else ""}
then just rerun your alembic migrations:
alembic revision --autogenerate -m "create initial tables"
when you go to look at your migration file you should see sqlalchemy_utils already imported via the mako script.
hope that helps.
Adding import sqlalchemy_utils in the script.py.mako file will automatically import this line on all the migration files that are generated and resolve the issue.
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
${imports if imports else ""}
Add the import sqlalchemy_utils line to the newly-created migrations/versions/{hash}_my_comment.py file. However, this will only fix the problem for that specific step of the migration. If you expect that you'll be making lots of changes to columns which reference sqlalchemy_utils, you should probably do something more robust like Walter's suggestion. Even then, though, it looks like you may need to add code to properly deal with each column type you end up using.
NB: Despite seeing the suggestion in multiple places of just adding the import line to the script.py.mako file, that did not work for me.

import * as x and {y,z} from 'file'

In short, how can I combine these two lines of code?
import * as php from './php';
import {str_replace, trim} from './php';
I can't find a syntax that works. I've tried things like
import {str_replace, trim}, * as php from './php';
N.B. this is ECMAScript 2015 (6th Edition, ECMA-262).
You cannot combine these in ES6 indeed. You can only use namespace imports or named imports together with a default import, but not with each other.
The solution is either to keep the two lines, or just use php.str_replace and php.trim everywhere in the code and drop the named imports.

Unable to import react-native-vector-icons using es6

I'm trying to use react-native-vector-icons with ES6 in React Native, but unfortunately I'm having trouble importing the icons. Their documentation still uses the old require statement, so I don't think it's helpful.
This is my import:
import {Ionicons} from './node_modules/react-native-vector-icons/Ionicons.js';
This is my usage:
<Ionicons name="ios-book" color="#4F8EF7" />
The error I receive is:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
It's clear that Ionicons is undefined, so I'm aware that fundamental about the import statement is wrong.
import Ionicons from 'react-native-vector-icons/Ionicons';
import {x} from 'abc'; translates to var x=require('abc').x, not to var x=require('abc').
So what about :
import * as Ionicons from './node_modules/react-native-vector-icons/Ionicons.js';
I ended up using an import statement as follows:
import {default as Icon} from '../node_modules/react-native-vector-icons/Ionicons';
This is because after I followed #Olivier's advice, I ended up with an object that contained a number of properties and I couldn't just use <Icon> as a component, but I discovered that <Icon.default> worked.
Thanks to all who answered!

Why won't my default class import in ES6?

I'm working with babel-loader inside webpack for the first time, and I'm very new to ES6 as well. I'm trying to export a base class from one file and import it into another. Exporting and importing has worked fine throughout my file thus far, and I am just now hitting a problem with it for the first time while trying to create classes.
Here's what my code looks like:
BaseClient.js
export default class BaseClient {
// snip...
};
SessionClient.js
import BaseClient from './BaseClient';
// outputs "undefined":
console.log(BaseClient);
// throws "Uncaught TypeError: Super expression must either be null or a function, not undefined":
export default class SessionClient extends BaseClient {
// snip...
};
Am I doing something wrong? Is there any relevant information I'm missing from my question that's needed before diagnosing? Thanks!
Yeah, I met the issue as well. It's caused by circular reference between different files in very long reference chain.
Like following: