Compiling nodejs code for safer distribution - javascript

Is there any software that I can use to compile nodejs program?
The reason I want to compile nodejs code is to make it safely distributable.
For example for a desktop application,etc.
And also I want to know whether nodejs will execute faster if compiled as it is asynchronous already?

Javascript is not a compiled language and Node.js is Javascript. It will be executed and interpreted at runtime. You can process your javascript with tool like grunt.js for example lint-test and uglify it, but be careful so that do not break the npm system since it is based on certain conventions.
To package your javascript for distribution in the node.js context build an npm module.
https://www.npmjs.org/doc/developers.html
For distributing javascript to the desktop client: Remember it's Javascript an it need to be executed in the Javascript VM. So to have some UI you need to run it in the browser or you need to have some webkit compiled dll to run your code...
something like this...
http://www.tidesdk.org/
You can also use: http://github.com/rogerwang/node-webkit (Thanks to #edi9999)

There is no way to do that with v8, it has only JIT option. It possible to make a "snapshot" with v8, but it's not exactly the same as compilation and node.js doesn't have support for this feature (also it might produce slower code). Also all your code will be available with toString() of functions.
You might be interested in JXcore project. It is a fork of node and as far as I know has some solution to code protection. Also one of the project goals is to develop javascript-to-LLVM compiler. Of course it can't have full support for ES specification (eval, new Function etc).

There's no way to 'compile' a nodejs program, as the javascript is interpreted at run time.
However, if you want to protect your code, you could maybe use something like Uglify JS to make the javascript less readable. However, this won't hinder people to change around your code.

The closest you might get to acheiving your goal is to create a self-executing Javascript bytecode wrapper.
A project that does this is pkg
It somehow creates a self-contained binary executable from Javascript, including module dependencies and asset files and produces a self-contained executable.
Installation and use is easy:
$ npm install -g pkg
$ pkg index.js -o my-program
$ ./my-program
It seems the resulting binary contains nodejs bytecode. It appears that you can cross-compile.

Related

Convert npm packages to plain JS source tree

Is there any canonical way to create a plain, non-minified JS source tree (eg. using ES modules), that just runs on the desired target (nodejs / browser) from NPM packages?
I like do work in a small non-IDE environment, and never use packaging by myself for small projects. But third-party code is almost always shipped JS and TypeScript inside npm packages that use sophisticated build environments (just got npm, tsc, yarn, parcel, rollup, ... needed to build a single 3rd-party module).
So I would like to have all those build tools "do less" and just emit plain, human-readable JS with somewhat sane file structure (eg. like single file or original source tree). Basically convert a bunch of referencing npm packages to a sane source code tree that doesn't need megabytes of tooling to build itself anymore.
Any ideas welcome!

Is there a way to use Dart Sass command line version with web pack?

From the dart-sass documentation we see that the dart-sass has a command-line version and is more performant.
I want to know if we can somehow use that command-line version with the existing webpack set up to speed up our build-time performance.
I can install dart libraries in the build machine. But is there any webpack plugin which can leverage that and use the machine dependencies to build sass rather than dart-sass npm?
It seems as though the dart-sass team is working to support this case (see this issue). But the work isn't finished.
But is there any webpack plugin which can leverage that and use the machine dependencies to build sass rather than dart-sass npm?
Not that I can find. However, it would be possible to create your own loader which uses the dart executable (the source for sass-loader is a good point of reference, and not very complicated). Since the dart cli takes options to read from stdin (sass --stdin), you should be able to pipe to the cli and pass back the output.
There might be other ways to accomplish your aim with a webpack extension, but using a loader seems the most straightforward in my view.
Is this faster than using the js api that sass-loader uses? Well, according to the benchmarks, the advantage of the executable varies between 1.7 and 4.1 times faster (excluding the simplest case in which the executable runs 24 times faster, but is still sub-second execution for all cases). But there will be overhead for process generation, so you would have to measure to see what is faster in your case.

Compiling Modular Client-side Javascript

In Node.js, you can dynamically "require()" any javascript file likewise to PHP's require. I'd like to use this in my client-side code just for ease of development but not actually call a javascript function, but have a compiler replace the line with the contents of the respective file; effectively concatenating the files, not one after another, but inline within the code of one of the files. The closest thing I have found to this is smash. Are there any compilers, minifiers, etc that can do this?
Browserify might not be exactly what you want but it does definitely help with the ease of development issue. When you use Browserify, your code is your build tool. Browserify gives you all the benefits of writing code in node (no anon functions to avoid globals, npm, simple requires, imports instead of namespaced globals) and it allows you to package that code to run on the client with one command and only load one file.
You can checkout my open source js framework Luc JS for an example. It runs on node and IE6. I'm able keep the code modular and build the single browser file with a one line command.

how to create an environment agnostic javascript library

I'm creating a javascript library, and i want it to be environment agnostic (It will not use DOM, AJAX, or NodeJS api. It will be vanilla javascript). So, it's supposed to run in any javascript environment (browsers, npm, meteor smart packages, V8 C bindings...).
My currently approach is creating git repo with the library, with all the library inside a single global variable, without thinking about patterns like CommonJS or AMD.
Later, i'll create another git repo, using my library as a git submodule, and create what is needed to release it as a npm module. I'm concerned if it's a good approach, i didn't found anyone doing this way.
Pros: code will be vanilla javascript, without awareness of environment patterns. It will not bind itself to CommonJS. It will be repackable (copy and paste or git submodule) to any javascript environment. It will be as small as needed to be sent to browsers.
Cons: I'll have to maintain as many git as environments i want to support. At least a second git repo to deliver on npm.
Taking jQuery as example, it runs in both browser and nodejs, with just one git repo. There is some code to be aware of the "exports" variable to run on nodejs or other CommonJS compatible enviroment.
Pros: Just one git repo to mantain.
Cons: It will be binded to CommonJS pattern (to achieve npm compatibility)
My question is: Am i following a correct (or acceptable) approach? Or should i follow jquery's path, and try to create a single git repo?
Update 1:
Browserify and other require() libraries are not valid answers. My question is not how to use require() on the browser, instead, it's about the architecture pattern to achieve enviroment agnosticism.
Update 2:
Create a browser/nodejs module is not the question, it's known. The question is: can make a real enviroment agnostic library? This example is binded to CommonJS pattern, used in NodeJS.
If you are looking for design recommendation for your future library work then in my opinion you can think-future and just use usual Object Oriented Practices well proven in other languages, systems and libraries.
Mainly concentrate on the UML view of your design.
Forget the "one variable" requirement.
Use features proposed in the planned next version of JavaScript.
http://wiki.ecmascript.org/doku.php?id=strawman:maximally_minimal_classes
http://wiki.ecmascript.org/doku.php?id=harmony:modules_rationale
There is an experimental compiler available that allows you to write ES6-style code even today (see https://www.npmjs.org/package/es6-module-transpiler-rewrite).
Node.js has a --harmony command line switch that allows for the same (see What does `node --harmony` do?)
So in my opinion correct approach is to follow best practices and "think future"
"Use a build tool" is the answer for this question. With a build tool, you can develop with the best code pratices, without accopling your code to some enviroment standard of today (AMD, commonjs...) and still publish your code to these kind of enviroments.
For example, I'm using Grunt.js to run some tasks, like build, lint, test, etc.
It perform tedious operations (minification, compilation...) like Make, Maven, Gulp.js, and various others.
The build task can handle standards (like commonjs) for the compiled code. So, the library can be totally enviroment agnostic, and the build process handle enviroment adaptations.
Note that i'm not talking about compiling to binaries. It's compiling source to another source, like CoffeScript to JavaScript. In my case, it's compilation of JavaScript without enviroment standard to JavaScript with commonjs standard (to run as a Node.js module).
The final result is that i can compile my project to various standards without messing with my code.
Aditionally, with a build phase i can "think-future", like xmojmr answered and use the EcmaScript 6 features on my JavaScript code, using Grunt plugins like grunt-es6-transpiler or grunt-traceur to compile JavaScript code from ES 6 to 5 (so it can run on enviroments of today)
According to modular your library (if you need modules). Read this question Relation between CommonJS, AMD and RequireJS?
Take bootstrap for example, it uses npm to manage project dependencies and use bower to publish as static content for other web apps.
Take a look at browserify as reference, it's a little heavy because it provides the capability to bundle dependent npm modules as resource for browsers.

How can I use npm for front-end dependencies?

I want to ask if it is possible (and generally a good idea) to use npm to handle front-end dependencies (Backbone, jQuery).
I have found that Backbone, jQuery and so on are all available through npm but I would have to set another extraction point (the default is node_modules) or symlink or something else...
Has somebody done this before?
Is it possible?
What do I have to change in package.json?
+1 for using Browserify. We use it here at diy.org and love it. The best introduction and reasoning behind Browserify can be found in the Browserify Handbook. Topics like CommonJS & AMD solutions, build pipelines and testing are covered there.
The main reason Browserify works so well is it transparently works w/ NPM. As long as a module can be required it can be Browserified (though not all modules are made to work in the browser).
Basics:
npm install jquery-browserify
main.js
var $ = require('jquery-browserify');
$("img[attr$='png']").hide();
Then run:
browserify main.js > bundle.js
Then include bundle.js in your HTML doc and the code in main.js will execute.
Short answer: sort of.
It is largely up to the module author to support this, but it isn't common. Socket.io is an example of such a supporting module, as demonstrated on their landing page. There are other solutions however. These are the two I actually know anything about:
http://ender.no.de/ - Ender JS, self-described NPM analogue for client modules. A bit too involved for my tastes.
https://github.com/substack/node-browserify - Browserify, a utility that will walk your dependencies and allow you to output a single script by emulating the node.js module pattern. You can use a jake|cake|rake|make build script to spit out your application.js, and even automate it if you want to get fancy. I used this briefly, but decided it was a bit clunky, and became annoying to debug. Also, not all dual-environment npm modules like to be run through browserify.
Personally, I am currently opting for using RequireJS ( http://requirejs.org/ ) and manually managing my modules, similar to how Mozilla does with their BrowserQuest sample application ( https://github.com/mozilla/BrowserQuest ). Note that this comes with the challenge of having to potentially shim modules like backbone or underscore which removed support for AMD style module loaders. You can find an example of what is involved in shimming here: http://tbranyen.com/post/amdrequirejs-shim-plugin-for-loading-incompatible-javascript
Really it seems like it is going to hurt no matter what, which is why native module support is such a hot topic.
Our team maintains a tool called Lineman for building front-end projects. The tool is node-based, so a project relies on a lot of npm modules that operate server-side to build your assets, but out-of-the-box it expects to find your client-side dependencies in copied and committed to vendor/js.
However, a bunch of folks (myself included) have tried integrating with browserify, and we've run into a lot of complexity and problems, ranging from (a) npm modules being maintained by a third party which are either out of date or add unwanted changes, to (b) actual libraries that start failing when loaded traditionally whenever a top-level function named require is even defined, due to AMD/Require.js baggage.
My short-term recommendation is to hold off and stick with good ol' fashioned script concatenation until the dust settles. Until you have problems big enough or complex enough to warrant it, I suspect you'll spend more time debugging and remediating your build than you otherwise would. And I think most of us agree the best use of your time is focusing on your application code, not its build tools.
You might want to take a look at http://jspm.io/ which is a browser package manager. Has nice ES6 support too.
I personally use webmake for my small projects. It is an alternative to browserify in the way it brings npm dependencies into your browser, and it's apparently lighter.
I didn't have the opportunity to compare in details browserify and webmake, but I noticed webmake doesn't work well with modules internally using global variables such as socket.io (which is full of bloat anyway IMO).
I would be cautious about RequireJS, which has been recommended above. Because it is an AMD loader, your browser will load your JS files asynchronously. It will induces more exchanges between your client and server and may degrade the UX of people browsing from mobile networks / under bad WiFi. Moreover, if you succeed to keep your JS code simple and tiny, asynchronous loading is absolutely not needed !

Categories