Short Notes on JS
From PaskvilWiki
Simple Mapping
let a = {a: 1, b: 2, c: 3};
Object.keys(a).map(i => console.log(i));
> a
> b
> c
>> [undefined, undefined, undefined]
a = [1, 2, 3];
a.map((i, k) => console.log(i, k));
> 1 0
> 2 1
> 3 2
>> [undefined, undefined, undefined]
// fill() is required here, as it materializes the Array;
// otherwise, Array(8) would be treated as empty array by map()
Array(8).fill().map((_, i) => i * i);
>> [0, 1, 4, 9, 16, 25, 36, 49]
== Fetch Patterns ==
<pre>fetch("url", { options... })
.then((response) => {
if (!response.ok)
throw new Error('Network response was not ok');
return response.json(); // or response.blob(), etc.
})
.then((data) => {
// do something with the data received
})
.catch((error) => {
console.error('Failed to fetch:', error);
});
Environment Variables in WebPack
WebPack does not have access to environment (duh), so you need to "bake" any relevant environment variables in the WebPack during build:
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
STAGE: JSON.stringify(process.env.STAGE),
// ...
}
})
Debugging in VS Code on Linux
- install Debugger for Chrome extension
- open the launch.json file, and edit as follows:
- custom profile - user-data-dir - is used, to make sure you have clean (enough) slate
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"runtimeExecutable": "/usr/bin/chromium-browser",
"runtimeArgs": ["--remote-debugging-port=9222", "--user-data-dir=/home/user/tmp/remote-profile"],
"name": "Launch Chrome against localhost",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}"
}
]
}
- run the npm (the port used should correspond to the url key above)
- hit debug in VS Code, add breakpoints, etc., and enjoy!
- this will actually open new browser window, as subwindow of VS Code, neat!