I'd like to:
insert debug logging statements into my code that I want to be able to turn on and off during development; and
then have these statements stripped out entirely in production.
To accomplish stripping out the logs for production, I've seen that the React project itself uses this idiom:
if ("production" !== process.env.NODE_ENV) {
// warn or log or whatever
}
By compiling the modules with process.env.NODE_ENV set to "production" and then running the bundle through a dead code eliminator like UglifyJS, the logs will be eliminated as unreachable.
This is fine, but are there more flexible solutions? I'm thinking something like the debug() Node module, or really some even more powerful, like the Java logging APIs.
I am wondering why I'm not finding a module that combines the ("production" !== process.env.NODE_ENV) approach with debug().
var debug = function(msg) {
if ("production" !== process.env.NODE_ENV) console.log(msg);
}
module.exports = debug;
Usage:
var debug = require("debug");
debug("some logs");
Sorry, I couldn't help myself ;). But really, there are plenty of JS logging frameworks out there (although I honestly think the solution above is simple enough that you don't need to over-complicate things).
Coming from a Java world, I was pleased to see there is a 'log4javascript' project.
http://log4javascript.org/
It has some cool stuff including a logging console with some features...
Related
So what I want to ask is: Is there a way to convert this simple file into a library which can work with Browsers (script tag), Node JS and Single Page Applications using single codebase?
Until now, all I have been doing was using libraries but it never came to my mind that it isn't actually that simple to make one. I am working on a React application where I created a simple helper file with exports. I thought "why not make it an independent library in NPM?". Just as I started testing it independently in NodeJS environment, I came to realize that there is actually a lot of difference in the way both environments make imports.
I have slight knowledge of Webpack, but I don't know how to approach it. Would I need different codes for different environments?
Another thing that confused me was when I thought about "How do we actually import things/functions from libraries?" Like when we install any library from NPM INSTALL and we do "import { abc } from 'library'", does it look for an index.js file in the library folder or what? Or in case of Node, "let lib = require('library')", where it does it look since its a different environment than SPA?
In conclusion, I have a simple single file I want to launch in NPM as a library which could work in any environment.
This is a very broad question, so a very broad answer: Look at tools like webpack, rollup, and browserify which are often used to make Node.js things available in the browser.
Another possibility is to look at how a module like slug is coded such that it works in the browser and in Node.js, but requires some hacks (and a decent test setup) to do it. For example, it checks typeof window !== 'undefined' to switch between code that needs to run in the browser vs. code that needs to run in Node.js. And this bit at the end detects the module system being used and acts accordingly:
if (typeof define !== 'undefined' && define.amd) { // AMD
define([], function () { return slug })
} else if (typeof module !== 'undefined' && module.exports) { // CommonJS
module.exports = slug
} else { // Script tag
root.slug = slug
}
sorry a rookie question, I am using react and typescript (via create-react-app) and if I have some totally non-UI javascript code (a module I am working on to work with some REST api), something along the lines like this:
src/lib/rest.tsx
export const getUser = async function (
username: string,
) {
let response = await fetch(`http://localhost:3000/api/auth/`, {
username
});
return response;
};
I am wondering how can I test this function locally in a REPL or browsers's dev tools, before putting it into real use. I think I have two difficulties right now:
webpack seems not even packaing this module into the code now, if I open Chrom's dev tools I can see other tsx files but not this one, simply becasue I am not importing this module anywhere I think.
even if it is packaged I dont know how to import this module in a REPL or the dev tool console because first I dont know what is the correct syntax here, Would it be import src/lib/rest.tsx? Also seems I cannot import any module in a REPL because import can only happen inside a module.
The workflow here is just I have written some simple typescript function and I want to run them in a REPL like enviorment so I can make sure they are working before using it anywhere or starting to write unit/integration tests against them.
Thanks!
1 is correct, your new module is not imported and thus not bundled by webpack.
I don't think you could use import syntax in console atm. But there are 2 ways you could try.
Just import your code in one of the bundled file, if you are using dev server, change will be reflected to browser automatically:
import { getUser } from '../../lib/rest';
getUser().then(console.log);
Or attach it to window so you could play with it in console:
import { getUser } from '../../lib/rest';
if (typeof window !== 'undefined') {
window.getUser = getUser;
}
Basically I have a simple if statement in a file responsible for setting up some async queue behavior.
//queue.js file
if (!myEnv) {
console.log('queue env is not set');
return;
}
It's an old legacy NodeJs 12.18.x application and I want to allow the return statement to be valid syntax when I run npm test. Right now the test env spits out Syntax Error...return' outside of function'
Is there an easy workaround for this? The app is being sunsetted, so it doesn't make sense to turn this into a ton of work, just do the simplest solution and get out. If it helps there's an .eslintrc.js file and a .prettierrc.js file in the top level directory. Not sure if those files are impacting this error as it seems like from google it's a NodeJS error.
Right now I have a unit testing build environment using node.js and nodeunit. Very happy with these but now I need TCO. I know that TCO has been added into the ES6 standard, but I don't know how to allow it for use with my project. Tried the Harmony flag, but couldn't get it to work with nodeunit. Any help?
Got the idea for using Harmony here:
Node.js tail-call optimization: possible or not?
I like the way these guys think, but I can't do the first answer because then other working on the project would also be forced to change their nodeunit.cmd files (which may screw up other projects they are working on) and the second answer doesn't appear to work:
NodeUnit enable harmony features
From what I understand, it looks like you want to write unit tests in ES5 using nodeunit to test your code written in ES6.
If I understood well, then you can check out this post which shows how to achieve that.
This solution requires you to npm install traceur and then you can require() your ES6 module from within your tests like so :
var traceur = require('traceur');
traceur.require.makeDefault(function(filename) {
return filename.indexOf('node_modules') === -1; // Don't parse node modules
});
var myModule = require('./../path/to/my/module.js');
module.exports = {
// ... tests ...
};
Now you should be able to run that with nodeunit.
I'm curious if anyone else is using a similar approach to mine and or if anyone has a thought or suggestion to help improve the workflow. To my knowledge, this is a somewhat original method.
So basically, I'm using NodeJS to development my client side code. I use Grunt+watch to automatically concatenate and minify all of my projects source into a single .min file, which gets written to the public/js folder. However, for testing I use Jasmine-node and so I need to have an index file (for this purpose only) which requires all of the project source files. However, because I want the same code to run in both Node as well as the browser, I add everything to a global project namespace such as:
myApp.framework.someClass
Within the myapp.js file, I then export to node (if module + exports exists). This allows all of my objects to be exposed to node without having to add the module.exports stuff to every source file, and instead, I can either simple do:
(function() { myApp.framework.someClass = function() {...} })();
in each file, or even simply:
myApp.framework.someClass = function() {...}
This works incredibly well for the client because everything is already there in memory, however the downside is that in Node, sometimes trying to access another class within the myApp namespace will fail because I'm not using something like RequireJS to manage dependencies.
My thought was maybe to add requires to the files just as you would in a standard node app, but then in the build process, have any node specific stuff, stripped out.
Thoughts / comments please!
I have seen tricks like this being used to make the JS code be used in Node and browser environments. This is from async library:
// Node.js
if (typeof module !== 'undefined' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
https://github.com/caolan/async/blob/master/lib/async.js
Hope that helps!