whats the correct way to "shim" in systemjs? - amd

Sorry for the obfuscated question, I'll elaborate my problem. I am currently developing a single page app in Aurelia, and I found a lib I want to try out: https://github.com/hootsuite/grid. I did the normal jspm routine:
jspm install github:hootsuite/grid
which installs successfully and adds the following to the systemjs config:
map: {
"hootsuite/grid": "github:hootsuite/grid#1.0.0",
The package file looks like this:
define(["github:hootsuite/grid#1.0.0/src/gridList.js"], function(main) {
return main;
});
Which enables me import the module as expected:
import * as grid from 'hootsuite/grid';
So far so good, but the js file referenced by the module is not the one I am interested in (src/gridList.js), the src folder also contains a jquery plugin named "jquery.gridlist.js" which is the file I actually want to resolve. I managed to "fix/hack" it by adding an additional AMD module definition in the module file (grid#1.0.0.js):
define('gridlist', ["github:hootsuite/grid#1.0.0/src/gridList.js"], function(main) {
return main;
});
define(["github:hootsuite/grid#1.0.0/src/jquery.gridList.js", "github:hootsuite/grid#1.0.0/src/gridList.js"], function(main) {
return main;
});
This is not a viable solution because the jspm_modules are not a part of source-control, thus it will have to be patched manually for every dev. So, whats the best approach for this type of problem? Or which features am I missing out on which removes the problem entirely?

Related

Docusaurus v2 and GraphQL Playground integration

I'd like to render GraphQL Playground as a React component in one of my pages but it fails due to missing file-loader in webpack. Is there a way to fix this in docs or do I need to create new plugin with new webpack config?
Is it good idea to integrate Playground and Docusaurus at all?
Thanks for your ideas...
A few Docusaurus sites have embedded playgrounds:
Hermes
Uniforms
In your case you will have to write a plugin to extend the webpack config with file-loader.
Not sure if you found a better way but check out: https://www.npmjs.com/package/graphql-playground-react
You can embed this react component directly in your react app - It looks like Apollo also uses the vanilla JS version of this
I just had exactly the same problem. Basically, Docusaurus with a gQL Playground Integration runs fine in local but won't compile due to errors when running yarn build as above.
In the end I found the answer is in Docusaurus, not in building a custom compiler:
I switched from using graphql-react-playground to GraphiQL: package: "graphiql": "^1.8.7"
This moved my error on to a weird one with no references anywhere on the web (rare for me): "no valid fetcher implementation available"
I fixed the above by importing createGraphiQLFetcher from '#graphiql/create-fetcher' to my component
Then the error was around not being able to find a window component, this was an easy one, I followed docusaurus docs here: https://docusaurus.io/docs/docusaurus-core#browseronly and wrapped my component on this page in like this:
import BrowserOnly from '#docusaurus/BrowserOnly';
const Explorer = () => {
const { siteConfig } = useDocusaurusContext();
return (
<BrowserOnly fallback={Loading...}>
{() => {
const GraphEx = GraphExplorer
return
}}
);
}
This now works and builds successfully

Import TNS Modules in the same typescript file of the angular web app

Nativescript Angular is well known for its code sharing properties. I am trying to simplify my design by using only 1 typescript file instead of splitting into the .ts and the .tns.ts file.
I was trying to import { Page } from "tns-core-modules/ui/page"; in the .ts. When running on Android, the code works flawlessly, but if I ng serve for the web app, it says Module not found: Error: Can't resolve 'tns-core-modules/ui/page'.
The reason why I wanted to import the page module is because of setting the action bar properties
constructor(private page: Page) {
if (isAndroid) {
console.log("This is Android");
this.page.actionBarHidden = true;
}
}
I was hoping to import the tns-core-modules/ui/page and some other tns-core-modules in the same file as the angular web app. Is it possible to do so? Or is it a must to split into the .ts and the .tns.ts files?
You have to go with platform specific ts files, one for web and one for tns, Page won't be valid while running inside a browser (ng serve).
If you prefer to reuse most of your code, try writting a common / base ts component, extend platform specific ts files from the common / base ts component, inject Page only within the tns specific ts file.

How do I keep the packager from trying to include a file that doesn't exist?

I am trying to use socket.io-client in my React app and am running into an odd problem. Deep inside engine.io (required by socket.io-client) there is a file called websocket.js with the following bit of code:
if (typeof window === 'undefined') {
try {
NodeWebSocket = require('ws');
} catch (e) { }
}
Since window is not undefined, you might think that this code does nothing, but you’d be wrong.
My packager (the standard React Native packager, so far as I know) goes through all the Javascript files and looks for all the import and require commands, and packages up the files they refer to.
The ws module contains a file called WebSocket.js, which intended for Node.js and makes use of Node.js modules like url.js and http.js, which of course do not exist in React, so the attempt at packaging fails.
Deleting those five lines fixed the problem and everything worked, but there must be a better way. Can I tell the packager to exclude certain modules?
I wasn't able to reproduce your problem, but you can try to blacklist the ws package.
How to blacklist specific node_modules of my package's dependencies in react-native's packager?
You can try the below code :
if (typeof window === 'undefined') {
try {
var wsNode = 'ws' // store node module name in a string
NodeWebSocket = require(wsNode); // dynamic require will exclude the node module to get bundled in react-native
} catch (e) { }
}
I haven't solve my problem as posed, but I figured out what was going on, why I was having difficulties other users were not.
In the file node_modules/engine.io-client/package.json was the following entry:
"browser": {
"ws": false,
"xmlhttprequest-ssl": "./lib/xmlhttprequest.js"
},
My venerable version of the React packager did not understand the "false" to mean "skip including ws [WebSockets] when you are building for the client side". Upgrading the packager made the problem go away.

How to make a new Perfect Project from scratch (Swift server) in xcode?

Perfect is a new Swift Framework for creating a web/http server in swift. The documentation is not there yet and I find trouble with building a new project from scratch. I don't know which frameworks are necessary to import and which one is the entry point of the app. main.swift etc...
I'd like to make a new xcworkspace that will have my project, "a hello world server".
Problems I'm trying to tackle:
Which frameworks must be included?
How should I create a Perfect server, what's the entry point of the app?
How to create a "hello" root which responds with a "Hello World message"?
How should I make the target for the server and eventually run the server?
I managed to write a "Hello World" guide about this. http://code-me-dirty.blogspot.co.uk/2016/02/creating-perfect-swift-server.html
In a nutshell you need to proceed like this:
clone the original project
Create a new Workspace
Create a new Project
Import PerfectLib.xcodeproject & Import PerfectServer.xcodeproject but do not copy
Setup your project scheme to launch the PerfectServer HTTP App
Link the PerfectLib onn the "Linked Frameworks and Libraries" section
setup Build settings for your framework target*
Create PerfectHandlers.swift and paste(better write to get the feeling) the following code
import PerfectLib
//public method that is being called by the server framework to initialise your module.
public func PerfectServerModuleInit() {
// Install the built-in routing handler.
// Using this system is optional and you could install your own system if desired.
Routing.Handler.registerGlobally()
// Create Routes
Routing.Routes["GET", ["/", "index.html"] ] = { (_:WebResponse) in return IndexHandler() }
// Check the console to see the logical structure of what was installed.
print("\(Routing.Routes.description)")
}
//Create a handler for index Route
class IndexHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.appendBodyString("Hello World")
response.requestCompletedCallback()
}
}
Then you are ready to run. On my blog I have a long, more detailed version of this and I will update here if necessary.
Build Settings
Deployment Location: Yes
Installation Build Products Location : $(CONFIGURATION_BUILD_DIR)
Installation Directory : /PerfectLibraries
Skip Install : NO
I just wrote up a tutorial I want to share as another solution that outlines how to create a web service with Perfect and an app to interact with it.
http://chrismanahan.com/creating-a-web-service-swift-perfect
Summary
You must have your project in a workspace. This workspace should also include the PerfectServer and PerfectLib projects.
In your project, create a new OSX Framework target. This will be your server target
Link PerfectLib with both your server target and your app's target (if you're building an app alongside the server)
Edit your server's Run scheme to launch with PerfectServer HTTP App.
In your Server target's Build Settings, set the following flags:
Skip Install = No
Deployment Location = Yes
Installation Directory = /PerfectLibraries
Installation Build Products Location = $(CONFIGURATION_BUILD_DIR)
Create a new file in the server's folder. This file will handle requests that come in. Include [most of] the following:
import PerfectLib
// This function is required. The Perfect framework expects to find this function
// to do initialization
public func PerfectServerModuleInit() {
// Install the built-in routing handler.
// This is required by Perfect to initialize everything
Routing.Handler.registerGlobally()
// These two routes are specific to the tutorial in the link above.
// This is where you would register your own endpoints.
// Take a look at the docs for the Routes API to better understand
// everything you can do here
// register a route for gettings posts
Routing.Routes["GET", "/posts"] = { _ in
return GetPostHandler()
}
// register a route for creating a new post
Routing.Routes["POST", "/posts"] = { _ in
return PostHandler()
}
}
class GetPostHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.appendBodyString("get posts")
response.requestCompletedCallback()
}
}
class PostHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.appendBodyString("creating post")
response.requestCompletedCallback()
}
}
As you're building out different aspects of your service, you can test it by using cURL in the command line, or other REST testing tools like Postman
If you wanna dive deeper and learn how to integrate with a SQLite database or create an app that talks with your new server, check out the tutorial at the top of this post.
I would recommend staying away from the templates, as others suggested, and create a clean project yourself.
Create this folder structure:
MyAPI
├── Package.swift
└── Sources
└── main.swift
Then, in the Package.swift file
import PackageDescription
let package = Package(
name: "MyAPI",
targets: [],
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2)
]
)
And the main.swift file:
import PerfectHTTP
import PerfectHTTPServer
do {
let route = Route(method: .get, uri: "/hello", handler: { (request: HTTPRequest, response: HTTPResponse) in
response.appendBody(string: "world!")
response.completed()
})
try HTTPServer.launch(.server(name: "localhost", port: 8080, routes: [route]))
} catch {
fatalError("\(error)")
}
Go to the command line and run:
swift package generate-xcodeproj
Open the generated project file:
MyAPI.xcodeproj
Change the active scheme, then build and run:
Open in safari:
http://localhost:8080/hello
I'm not sure if you have found a solution or not, but this is what I did:
The 'Tap Tracker' app is an app written the the Perfect libraries, so even if documentation isn't ready yet you can still dissect the app. I renamed the app, and the classes/methods. There's a single index.html, which I moved into a 'www' root, and then rerouted the view with TTHandler to try and make a standard layout. It doesn't work very well because the framework is so young, but it can be done. I would be much more specific but I went back to rails for the time being because I want to wait until it's a little more mature.
It's fun to mess around with, and I will probably write my own library on top of perfect onc feature innovation calms down and I can make something stable with it.
Just copy all files from one of the sample-projects to your git repository:
https://github.com/PerfectExamples
Rename the example_project_name in all files (you've copied) to your project name.
In terminal run
swift package generate-xcodeproj
And you'll get a Perfect Project with the required name.

js in html is not executing in Phoenix framework sample app

I'm playing around with the phoenix framework. I copied the chat example entirely but I'm not getting any results.
In fact when I write console.log("testing") in my app.js I notice that my console does not log anything...
I am getting the error referenced in this link:
phoenix framework - invalid argument at new Socket - windows
However that error seems to be related to Brunch not working in windows. When I brunch build, I can confirm that app.js has the console.log("testing") that I included.
Nevertheless, I don't see that console log when I visit my localhost:4000.
Why is JS not executing?
Turns out the guide is missing a key line that made it not work.
The guide has the following:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="<%= static_path(#conn, "/js/app.js") %>"></script>
</body>
But that is missing the below line which you can put above the body tag.
<script>require("web/static/js/app")</script>
Even as Chowza already solved this question I would like to propose another, possible cleaner solution, using the autoRequire feature of Brunch.io.
The problem occurs because Brunch.io does not autoRequire the app.js under Windows correctly. Chowza worked around this issue by requiring the file manually in the html. You can omit the manual require if you alter the /brunch-config.js as follows: Change from
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
}
To
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"]
}
}
This way the app.js is autoRequired, even if you work on a Windows based system.
I would like to mention, that this solution is based on the link Chowza himself posted, so all credit goes to him for pointing to the link.

Resources