In order to try a javascript example I found here, I did the following things (following this answer, on Windows 7):
Installed node
Installed browserify.
Created a new directory Test.
Within this directory I run npm init.
Within this directory I created a file index.js with the exact content as shown on the example page ate the bottom.
I ran the following commands:
npm install colormap
browserify -s index.js > bundle.js
I created a html code example.html as follows (in the same directory):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
<img id="background" readsrc="satellite-view-of-earth-at-night.jpg" width=480></img>
<img id="canvasImg" name="colormap" alt="image for download">
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
opened the file example.html and just saw an empty blank white page with the text image for download. No colormaps. No error on the konsole either!
How to fix this code, how to do it right? Maybe I did forget to install something? Did something in the wrong order? Forgot to do something else?
colormap is a NPM module for generating colormaps. It includes a few pre-generated colormaps in the \res directory, but in general you need to do something like the following to generate a json array which represents a colormap. After steps 1 to 6 above, create a new .js file with the following contents and run it to create a custom colormap:
let colormap = require('colormap')
var fs = require('fs');
let colors = colormap({
colormap: 'jet',
nshades: 256,
format: 'hex',
alpha: [1.0, 0.5, 1.0]
})
var json_text = JSON.stringify(colors);
fs.writeFile("jet.json", json_text, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Related
I am following a simple online tutorial. Nothing fancy is going on and I am not using Node or React. The guy is using Sandbox but I am just using Brackets and a folder on my desktop to contain my files. Everything is fine until I have to export a class from one script (paddle.js) to the main script (index.js). Prior to changing the first lines, I just have a blank canvas in the browser, as expected. After changing the first lines (by inserting export/import commands, respectively) I get the following errors in Chrome:
Uncaught SyntaxError: Unexpected identifier index.js:1
Uncaught SyntaxError: Unexpected token export paddle.js:1
here is my script paddle.js:
export default class Paddle {
constructor(gameWidth, gameHeight){
this.width = 150;
this.height = 30;
this.position = {
x: (gameWidth - this.width) / 2,
y: gameHeight - this.height - 10,
};
}
draw(ctx){
ctx.fillRect(this.position.x,this.position.y,this.width,this.height);
}
}
here is my script index.js:
import Paddle from 'paddle';
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext('2d');
const GAME_WIDTH = 800;
const GAME_HEIGHT = 600;
ctx.clearRect(0,0, GAME_WIDTH,GAME_HEIGHT) //clears region between corners of screen, necessary fro re-drawing because screen does not 'reset' until I tell it to.
let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);
paddle.draw(ctx);
here is my html file, index.html (mostly boilerplate):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#gameScreen{
border: 1px solid black;
}
</style>
<title>breakout tutorial</title>
</head>
<body>
<canvas id = "gameScreen" width="800" height="600"></canvas>
<script src = "index.js"></script>
<script src = "paddle.js"></script>
</body>
</html>
I am supposed to get a blue paddle at the bottom of the screen, like in this guy's video:
https://www.youtube.com/watch?v=3EMxBkqC4z0
EDIT: #Talgat Saribayev So I am trying to follow your advice and am running HTTP server from the console. I set the directory to the "/src" directory of the attached zip, which I have on my desktop. I am getting "404 not found" errors. I think this is an easy fix but I don't know what to do. Probably the import lines in the classes. Help?
https://drive.google.com/file/d/1xKGUpfmjHggY50lUyFrAKFqo_msPjZKS/view?usp=sharing
Ok there is answer from hatinacat2000, but you can enable ES6 import export natively on Chrome. I will try to explain each step and configuration in order to run you code.
Add type="module" to your script tags
<script type="module" src = "index.js"></script>
<script type="module" src = "paddle.js"></script>
In order to enable ES6 modules. For more info: https://medium.com/dev-channel/es6-modules-in-chrome-canary-m60-ba588dfb8ab7
Load throw some server, or will face CORS issue. Try this https://www.npmjs.com/package/http-server
Also you need to update import in your code of index.js
import Paddle from './paddle.js';
That's it, now you can use ES6 modules natively.
EDIT Ther rest of the instructions specifically for hatinacat2000 case.
Unzip files into any directory, open terminal and move to MyFiles
Move you asset directory/folder into src.
$ tree ./src -L 1
./src
├── assets
├── ball.js
├── game.js
├── index.html
├── index.js
├── input.js
└── paddle.js
Change all imports in js files to relative. Don't forget .js extension. For example for game.js
import Paddle from "./paddle.js";
import InputHandler from "./input.js";
import Ball from "./ball.js";
Run your http-server. $ http-server ./src and open in browser http://localhost:8080/
That what I've got
In the tutorial, this guy is using an IDE that may be in the browser or through some fancy file management. He needs to use import/export. I don't need to do that because all of my scripts are in the same directory. So I took those import/export commands out. What I DID need to do was load the "Paddle" class into the HTML file ahead of the other .js file (index.js) that uses it (duh, I loaded them in reverse order). When I do, I get this:
Now, I understand that this solution is pretty common on stack overflow so I want to say how much I appreciate everyone who has the experience to read our chicken scratch and say "hmm, bet you forgot to 'x,y,z'!". As I continue to grow I will anticipate solutions to import/export command trouble being of this kind.
The following Angular application is working correctly, but I need to achieve some requirements that don't depend on me:
GitHub Repo: git#github.com:napolev/napolev.pr02.git
[1] need to move: main.ts from: /src/ to: /src/app/
[2] need to get rid of the file: tsconfig.app.json.
Probably this file is partially referenced on the file: .angular-cli.json (with ext: .spec.json instead of: .app.json, why?)
I tried to remove it but then I get a build error:
> ng build
ENOENT: no such file or directory, stat 'D:\wamp64\www\ionic2\cli-angular-counter\src\tsconfig.app.json'
Error: ENOENT: no such file or directory, stat 'D:\wamp64\www\ionic2\cli-angular-counter\src\tsconfig.app.json'
at Error (native)
at Object.fs.statSync (fs.js:987:18)
at AotPlugin._setupOptions (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#ngtools\webpack\src\plugin.js:58:16)
at new AotPlugin (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#ngtools\webpack\src\plugin.js:26:14)
at _createAotPlugin (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-configs\typescript.js:55:12)
at Object.exports.getNonAotConfig (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-configs\typescript.js:70:19)
at NgCliWebpackConfig.buildConfig (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-config.js:27:37)
at Class.run (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\tasks\build.js:26:92)
at Class.run (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\commands\build.js:143:26)
at Class.<anonymous> (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\ember-cli\lib\models\command.js:134:17)
at process._tickCallback (internal/process/next_tick.js:103:7)
One question:
[3] For the rendered html file, where is specified the inclusion of the following files?
inline.bundle.js
polyfills.bundle.js
vendor.bundle.js
main.bundle.js
This is the rendered code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular Counter</title>
</head>
<body>
<app-root>Loading...</app-root>
<script type="text/javascript" src="inline.bundle.js"></script>
<script type="text/javascript" src="polyfills.bundle.js"></script>
<script type="text/javascript" src="vendor.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
</html>
Please, if possible, use the reference numbers above (inside square brackets) in your answers. If possible maybe you could provide me the modified code?. I tried to put this code on: plnkr.co/edit/ with no success.
[EDIT]
I solved the points [1] and [2] by doing the following changes:
http://github.com/napolev/napolev.pr02/commit/068d0884e360a2ec438032f209601b6b26ec5398
going from: [Commit 1] to [Commit 2][2], but now the lint test tool doesn't work properly because it doesn't detect a violation of a tslint.json declared rule. For example,
https://github.com/napolev/napolev.pr02/blob/068d0884e360a2ec438032f209601b6b26ec5398/src/app/counter.component.ts#L55
There you can see a line with a tab character (illegal based on my declared rules on the tslint.json file). On the previous commit it would be detected.
How can I make the lint tool work again?
I am trying to use express-babelify-middleware
with FeathersJS and the error shows up in the browser console:
ReferenceError: main_run is not defined
I take this to mean that babelify is not working or I am using it incorrectly as main_run is in the global namespace of the src in my html file.
Here is my setup using the structure from feathers generate:
public/index.html:
<!DOCTYPE html>
<html>
<head>
<title>babelify test</title>
<script src="main.js"></script>
<script>
main_run()
</script>
</head><body>
<p>Testing feathers with babelify</p>
</body></html>
public/main.js
const external_module = require('./test')
function main_run(){
external_module()
}
public/test.js
module.exports = function(){
console.log("Hello world for an external module")
}
among the .uses of src/app.js:
...
const babelify = require('express-babelify-middleware')
...
app.use(compress())
.options('*', cors())
.use(cors())
//the line that is not working:
.use('/main.js', babelify( path.join(app.get('public'), 'main.js') ))
.use(favicon( path.join(app.get('public'), 'favicon.ico') ))
.use('/', serveStatic( app.get('public') ))
When I visit localhost:3030/main.js I can see the file, but the functions look to be in a function of their own, so I don't know how to get into that function.
Silly problem, one can't access browserified code in the html file that calls it. So public/index.html can't access main_run unless it is attached to the window object. There is a similar question
here.
Other than that, my code works perfectly.
In main.js place the following code at the bottom:
window.main_run = main_run
Then in index.html replace the main_run() line with:
window.main_run()
This will write the contents of test.js to the console.
I made 4 javascript files, A,B,C,D, and they will export 4 modules A,B,C,D. Their dependency is A->B->C->D. I key in the command
browserify A.js -o bundle.js
and a bundle file include A,B,C,D is created. In the html file, i got
<script src="bundle.js"></script>
<script src="client.js"></script>
inside the client.js, i got
var a = new A();
the console will print an error that A is not defined.
However, the client.js will work if i delete the 'require' and module.exports on all js file and do this in html file
<script src = "D.js"></script>
<script src = "C.js"></script>
<script src = "B.js"></script>
<script src = "A.js"></script>
<script src = "client.js"></script>
Does anyone have any idea about this issue?
You have to create a standalone bundle which will add a variable to the global execution context, this is done with the --standalone <name> option
browserify A.js --standalone A -o bundle.js
Besides the standalone option that Mauricio proposed, you can also have browserify create a require function so you can use the require function in the browser.
browserify -r ./A.js:a_module ./B.js ./C.js ./D.js -o bundle.js
Then your client.js file can do this:
var a_module = require('a_module');
var a = new a_module.A();
This is the external requires option.
I was following along to this post by Rebecca Murphey: http://blog.rebeccamurphey.com/scaffolding-a-buildable-dojo-application
I was substituting her file structure with my own.
Running the normal version of the scripts works fine, but the moment I compile them using the build tool, the script errors.
It's very likely a small problem with how the files are referenced via my Profile.js script but maybe someone here can help me get the settings correct before running the build tool so the compiled files will work as they should.
My file structure is as follows...
/www
/Assets
/Scripts
/Classes
build.sh
Init.js
Load.js
Profile.js
/Dojo
Dojo.js
/dojo-sdk
index.html
My index.html file has the following code...
<script>
var djConfig = {
modulePaths : {
'Integralist' : '../Classes'
}
};
</script>
<script src="Assets/Scripts/Dojo/Dojo.js"></script>
<script>
dojo.require('Integralist.Init');
</script>
...and the Init.js file has the following code...
dojo.provide('Integralist.Init');
dojo.require('Integralist.Load');
dojo.declare('MyApp', null, {
constructor: function(config) {
this.version = config.version || '1.0';
this.author = config.author || 'Unknown';
}
});
var myapp = new MyApp({
author: 'Mark McDonnell'
});
alert(myapp.author);
alert(myapp.version);
...lastly, the Load.js file has nothing in it but this...
dojo.provide('Integralist.Load');
alert('I\'m the Load.js file');
...and this all runs fine. When I load index.html I get 3 alert messages, brilliant.
The problem occurs when I try to run the build tool.
Via Mac OSX i locate the /Classes/ directory and run 'sh build.sh' and the build.sh file within the /Classes/ directory consists of the following code...
cd ../../../dojo-sdk/util/buildscripts
./build.sh profileFile=../../../Assets/Scripts/Classes/Profile.js releaseDir=../../../Assets/Scripts/Release
...now, after running the build tool I have a new /Release/ directory created within my /Scripts/ directory, this /Release/ directory consists of...
/www
/Assets
/Scripts
/Release
/Integralist
/Classes
Init.js
Init.js.uncompressed.js
/dojo
--loads of dojo related files--
...I then created a separate index file called index-release-version.html and changed the script code as suggested by the article, so it looks like this...
<script src="Assets/Scripts/Release/Integralist/dojo/dojo.js"></script>
<script>
dojo.require('Integralist.Init');
</script>
...from here I get the following error...
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught Error: Could not load 'Integralist.Init'; last tried '../Integralist/Init.js'
...and just for reference my Profile.js file that is used by the build tool consists of the following (and it's here I think the problem may be)...
dependencies = {
stripConsole : 'all',
action : 'clean,release',
optimize : 'shrinksafe',
releaseName : 'Integralist',
localeList : 'en-gb',
layers: [
{
name: "../Classes/Init.js",
resourceName : "Integralist.Init",
dependencies: [
"Integralist.Init"
]
}
],
prefixes: [
[ "Integralist", "../Classes" ]
]
}
Any help really appreciated as I desperately want to get my head around how Dojo works :-)
Thanks!
M.
I'd suggest working from the repo I linked to from my blog post (http://github.com/rmurphey/dojo-scaffold) -- I double-checked that it's definitely working :) -- and make changes to it until your changes break something, rather than trying to create your own structure right off the bat.
At a glance, I'm not 100% clear why you've got a Dojo.js file inside your directory structure, (is this the base Dojo lib or something else?), but the rest of Dojo is located elsewhere. If you use the structure I proposed, you can safely remove the djConfig declaration when using the built files, but as Dan mentioned, you may need to keep it if you're using a different configuration.
Do you have that djConfig variable in your index-release-version.html? It looks like Dojo is trying to find init.js at ../Integralist/Init.js, but you somehow need to tell it to look in ../Classes/Init.js
This is what your modulePaths : {'Integralist' : '../Classes'} was doing in your Index.html