Wait for import before parsing next import's dependencies - import

I am converting some code to ES6 syntax using JSPM/SystemJS/BabelJS.
I have the following:
// main.js:
console.log('foo');
import * as Backbone from 'backbone';
import * as Cocktail from 'backbone.cocktail';
Cocktail.patch(Backbone);
console.log('bar');
import Application from 'background/application';
console.log('application:', Application);
// application.js:
console.log('baz');
export default {};
This code outputs baz foo bar application: {}.
I would like to output: foo bar baz application: {} such that Cocktail.patch is ran before any code in application.js
I am able to achieve this by re-writing my code as:
// main.js:
console.log('foo');
import * as Backbone from 'backbone';
import * as Cocktail from 'backbone.cocktail';
Cocktail.patch(Backbone);
console.log('bar');
System.import('background/application').then(function(Application){
console.log('application:', Application.default);
});
// application.js:
console.log('baz');
export default {};
However, this feels convoluted and incorrect. It's leveraging SystemJS explicitly rather than ES6 import/export syntax. How can I wait before parsing application.js using ES6 syntax?

import is not actually an expression, it is just mark for compiler, which modules should be imported before this code will run. This is similar to how var definition works. All variables is defined before all expressions in that scope, this is named variable hoisting.
So if you want to be sure, that your code will run before imports, you can move it into separate module
// setup.js
console.log('foo');
// backbone-patch.js
import * as Backbone from 'backbone';
import * as Cocktail from 'backbone.cocktail';
Cocktail.patch(Backbone);
console.log('bar');
// application.js:
console.log('baz');
export default {};
// main.js:
import './setup';
import './backbone-patch'
import Application from './application';
console.log('application:', Application);
Imports will be loaded in order of appearance and you will get the desired result

ES2015 (AKA ES6) imports are statically analyzed. They are not executed in the standard flow of a JavaScript code, but are rather analyzed and executed before any of the importing code is executed.
Using System.import makes the import "dynamic" and occur at runtime, thus allowing you to control the actual timing / order of events.

Related

Can Dart conditional imports use names?

Consider a conditional import statement. The following comes from the Dart language guide:
import 'src/hw_none.dart'
if (dart.library.io) 'src/hw_io.dart'
if (dart.library.html) 'src/hw_html.dart';
Is there a syntax to add a name to these imports? For example, I'd like to say something like the following:
import 'src/hw_none.dart' as my_prefix
if (dart.library.io) 'src/hw_io.dart' as my_prefix
if (dart.library.html) 'src/hw_html.dart' as my_prefix;
Unfortunately, the above doesn't compile. I haven't been able to find a variation that does compile.
Is there a way to name conditionally imported packages?
I've done something like this a few month ago, to implement mobile and web functionalities. Seems like you cannot name each import separately.
import 'package:flutter_fcm_web_example/notification_helper.dart';
import 'firebase_mobile_messaging.dart'
if (dart.library.html) 'firebase_web_messaging.dart' as notifInstance;
abstract class NotificationEncapsulation {
static NotificationHelper get instance =>
notifInstance.FirebaseMessagingHelper();
}

Undeclared type: createM3FromEclipseProject (Rascal)

In the following module, I tried to add myModel for debugging purpose to see the AST.
module FlowGraphsAndClassDiagrams
import analysis::flow::ObjectFlow;
import lang::java::flow::JavaToObjectFlow;
// Added to check the M3 model
import lang::java::jdt::m3::AST;
import List;
import Relation;
import lang::java::m3::Core;
import IO;
import vis::Figure;
import vis::Render;
import analysis::m3::TypeSymbol;
alias OFG = rel[loc from, loc to];
//To view the M3 model from the whole eclipse project
alias myModel = createM3FromEclipseProject(loc project);
....
When I import the above module in the rascal console, I get the following error:
Reloading module FlowGraphsAndClassDiagrams
|console:///|:Could not load FlowGraphsAndClassDiagrams
|console:///|:could not reimport FlowGraphsAndClassDiagrams
|project://my_project/src/FlowGraphsAndClassDiagrams.rsc|(428,26,<18,16>,<18,42>): Undeclared type: createM3FromEclipseProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredType/UndeclaredType.html|
I don't understand what the mistake is.
I think the problem lies with
alias myModel = createM3FromEclipseProject(loc project);
What are you trying to achieve with this alias? I think you don't want to use an alias, instead you want to do this:
m = createM3FromEclipseProject(|project://eLib|);
println(m);
http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Declarations/Alias/Alias.html
You can use alias to create a new name for types, while createM3FromEclipseProject(loc project) seems to be a declaration of a function. If you want to call a function, which you seem to be doing, you need to provide a variable/value as parameter: createM3FromEclipseProject(|project://eLib|) if you want to "create an M3" from eclipse project "eLib".
Both answers are right, you can't use aliases for global variables. If you want to make an global variable (which in most cases we advice against), you have to give the type of that variable. We only allow type inference for local variables.
So in your specific case it should be:
M3 myModel = createM3FromEclipseProject(|project://eLib|);
In most cases you want to do this in your main method instead of at module import time.

Usage of the `import` statement

Can someone explain me how the import statement works ?
For example I have a type User in the myapp/app/models package:
package models
type User struct {
// exportod fields
}
I have a type Users in the myapp/app/controllers package:
package controllers
import (
_ "myapp/app/models"
"github.com/revel/revel"
)
type Users struct {
*revel.Controller
}
func (c Users) HandleSubmit(user *User) revel.Result {
// Code here
}
This gives me the following error:
undefined: User
I tried to change the imports to the following code:
import (
. "advorts/app/models"
"github.com/revel/revel"
)
But get this error:
undefined: "myapp/app/controllers".User
Which I don't understand either. So, what is the difference between import . "something" and import "something" ? How to properly import my model in my case ?
Each package has a set of types, functions, variables, etc. Let's call them entities. Each entity can be either exported (its name start with an Uppercase letter), or unexported (its name start with a lowercase letter).
A package can only access the exported entites of another package. To do this, it needs to import it, which will make the exported entites available with the package name as identifier. Example:
import "github.com/revel/revel"
will get all exported entites of the revel package, which will be available using revel. prefix. As in revel.Controller, which is the Controller type defined in the revel package.
You can alias a package identifier by prefixing the import path with the wanted identifier. Example:
import rev "github.com/revel/revel"
will import all revel entites with the identifier rev. So revel.Controller becomes rev.Controller. It is useful if you have multiple package with the same name, or a package with an absurdly long name.
As a bonus, you can import a package anonymously, by aliasing it to the blank identifier:
import _ "github.com/revel/revel"
which will import the package, but not give you access to the exported entities. It is useful for things like drivers, which you need to import but never access. A frequent example is the database drivers, which register themselves to the database/sql package so you never need to access them directly.
And as a bonus' bonus, you can also import locally a package, by aliasing it with the . identifier. The exported entites will then be available without identifier, as if you defined them in the same package.
How to properly import your packages is up to you. The general convention is to never alias if you can manage it, to hide the package that you don't need to access but still need to import (database drivers), and that's all. You really never need to import locally a package, even if some tutorials or frameworks do it for simplicity's sake.

How do I import a Swift file from another Swift file?

I simply want to include my Swift class from another file, like its test
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel { }
PrimeNumberModelTests.swift
import XCTest
import PrimeNumberModel // gives me "No such module 'PrimeNumberModel'"
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel() // "Use of unresolved identifier 'PrimeNumberModel'"
}
Both swift files are in the same directory.
I had the same problem, also in my XCTestCase files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.
UPDATE Swift 2.x, 3.x, 4.x and 5.x
Now you don't need to add the public to the methods to test then.
On newer versions of Swift it's only necessary to add the #testable keyword.
PrimeNumberModelTests.swift
import XCTest
#testable import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
And your internal methods can keep Internal
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel {
init() {
}
}
Note that private (and fileprivate) symbols are not available even with using #testable.
Swift 1.x
There are two relevant concepts from Swift here (As Xcode 6 beta 6).
You don't need to import Swift classes, but you need to import external modules (targets)
The Default Access Control level in Swift is Internal access
Considering that tests are on another target on PrimeNumberModelTests.swift you need to import the target that contains the class that you want to test, if your target is called MyProject will need to add import MyProject to the PrimeNumberModelTests:
PrimeNumberModelTests.swift
import XCTest
import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
But this is not enough to test your class PrimeNumberModel, since the default Access Control level is Internal Access, your class won't be visible to the test bundle, so you need to make it Public Access and all the methods that you want to test:
PrimeNumberModel.swift
import Foundation
public class PrimeNumberModel {
public init() {
}
}
In the Documentation it says there are no import statements in Swift.
Simply use:
let primNumber = PrimeNumberModel()
Check target-membership of PrimeNumberModel.swift in your testing target.
In Objective-C, if you wanted to use a class in another file you had to import it:
#import "SomeClass.h"
However, in Swift, you don't have to import at all. Simply use it as if it was already imported.
Example
// This is a file named SomeClass.swift
class SomeClass : NSObject {
}
// This is a different file, named OtherClass.swift
class OtherClass : NSObject {
let object = SomeClass()
}
As you can see, no import was needed. Hope this helps.
According To Apple you don't need an import for swift files in the Same Target. I finally got it working by adding my swift file to both my regular target and test target. Then I used the bridging header for test to make sure my ObjC files that I referenced in my regular bridging header were available. Ran like a charm now.
import XCTest
//Optionally you can import the whole Objc Module by doing #import ModuleName
class HHASettings_Tests: XCTestCase {
override func setUp() {
let x : SettingsTableViewController = SettingsTableViewController()
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
SO make sure PrimeNumberModel has a target of your test Target. Or High6 solution of importing your whole module will work
I was able to solve this problem by cleaning my build.
Top menu -> Product -> Clean
Or keyboard shortcut: Shift+Cmd+K
As of Swift 2.0, best practice is:
Add the line #testable import MyApp to the top of your tests file, where "MyApp" is the Product Module Name of your app target (viewable in your app target's build settings). That's it.
(Note that the product module name will be the same as your app target's name unless your app target's name contains spaces, which will be replaced with underscores. For example, if my app target was called "Fun Game" I'd write #testable import Fun_Game at the top of my tests.)
Check your PrimeNumberModelTests Target Settings.
If you can't see PrimeNumberModel.swift file in Build Phases/Compile Sources, add it.
You need to add a routine for the compiler to reference as an entry point, so add a main.swift file, which in this case simply creates an instance of your test file:
main.swift
PrimeNumberModelTests()
Then compile on the command line (I am using El Capitan and Swift 2.2):
xcrun -sdk macosx swiftc -emit-executable -o PrimeNumberMain PrimeNumberModel.swift PrimeNumberModelTests.swift main.swift
In this case, you will get a warning: result of initializer is unused, but the program compiles and is executable:
./PrimeNumberMain
CAVEAT: I removed the import XCTest and XCTestCase type for simplicity.
So, you need to
Import external modules you want to use
And make sure you have the right access modifiers on the class and methods you want to use.
In my case I had a swift file I wanted to unit test, and the unit test file was also a swift class. I made sure the access modifiers were correct, but the statement
import stMobile
(let's say that stMobile is our target name)
still did not work (I was still getting the 'No such module' error), I checked my target, and its name was indeed stMobile. So, I went to Build Settings, under packaging, and found the Product Module Name, and for some reason this was called St_Mobile, so I changed my import statement
import St_Mobile
(which is the Product Module Name), and everything worked.
So, to sum up:
Check your Product Module Name and use the import statement below in you unit test class
import myProductModuleName
Make sure your access modifiers are correct (class level and your methods).
Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.
Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.
As #high6 and #erik-p-hansen pointed out in the answer given by #high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.
While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.

Play exception: '{' expected but 'import' found

It throws me the exception for line 3. The thing is i have just these lines:
package controllers
import play.api._
import play.api.mvc._
import views._
import models._
object Application extends Controller {
def index = Ok(views.html.index("grrr", "blabla"))
}
EDIT: index.scala.html
#import helper._
#main("Todo") {
<h1>Hello World</h1>
}
I'm using play 2.2.0 on windows xp (with sbt)
I think that problem is with yours line separator in IDE. I once change LF(Linux) to CR(Mac)(by mistake, not knowing that this has an impact on compilation) and struggle with the same problem. After changing to default sperator everything back to normal.
The first line in Play! template is reserved for the signature definition. This is also mentioned in the Welcome screen when you create a new Play Application.
Beside the question why you import the helper._, I would do the following:
Make the first line empty, or at least NO import statements.
Run play clean
After this it should work, I hope :-)
Further information:
Play framework template automatically imports models._ among other things
https://github.com/playframework/playframework/blob/1acfd1dc4264e7589876fb1f4ebf37e584ab8bc6/framework/src/play/src/main/scala/views/play20/welcome.scala.html#L81
If you know a bit scala (I don't yet): https://github.com/playframework/playframework/blob/9206bea8c9c88acdc6786ebb2554f081396e8f6a/framework/src/templates-compiler/src/main/scala/play/templates/ScalaTemplateCompiler.scala
EDIT: 2013.09.24 at 22:15
You are passing two arguments to your view template (views.html.index("grrr", "blabla")), (views are compiled to functions). So in your function (`index view') the first line SHOULD define the function signature (arguments). I think that you should write your template as:
#(firstString : String, secondString : String)
#import helper._
#main("Todo") {
<h1>Hello World</h1>
}