Node.js, coffeescript and compiled js files - javascript

I understood it was possible to natively use CoffeeScript instead of JavaScript, without compiling the CoffeeScript files to JavaScript (at least not compiled them as files; Maybe in-memory or on-the-fly compilation).
I have a basic app with a main app.coffee file as following:
coffee = require 'coffee-script'
coffee = require 'coffee-script/register'
express = require 'express'
compression = require 'compression'
sockets = require 'socket.io'
http = require 'http'
server = http.createServer express
app = express()
# [...]
In my package.json I have the following:
// ...
"dependencies": {
"coffee-script": "^1.9.3"
// ...
}
"scripts": {
"start": "coffee app.coffee --nodejs"
// ...
}
// ...
I can run the app using $> nodemon app.coffee
or $> coffee app.coffee
or $> npm start
At some point when I re-run the application or save a CoffeeScript file, CoffeeScript file is compiled to a JavaScript file, and therefor every file in the folder tree end up getting duplicated in both a .js and a .coffee version, which I find pretty disturbing.
Also once there is a .js file for a module, I sometime feel like the application will use it in priority, and that changes in the CoffeeScript file are no longer taken in account.
How can I avoid this behavior, and avoid file to be compiled every time ? Is it possible for the node engine to natively use the CoffeeScript files without creating a .js copy in the file tree?
Of course I understand that the Node.js engine is a JavaScript engine, but is there a way to maybe compile/run files directly in-memory or in a different folder (since it might still be interesting to see the JavaScript output)?
What is the exact interaction between the Node.js engine, the CoffeeScript compiler, and how can I understand this behavior ?

I often use a small .js file to launch my code making the command to start my applications node index.js which contains this:
CoffeeScript = require('coffee-script');
CoffeeScript.register();
require('./src/main');
Change ./src/main to the path to your coffee file.
It uses your coffee files to run your code giving stack traces etc.. that correspond to your coffee source.
Your app.coffee would not need to require coffee-script as you are already using coffee at that point.

Related

How webpack dev vs production builds javascript code?

I'm building an HTML web application and writing all my code in TypeScript. I use webpack to convert the TypeScript to JavaScript and to bundle and minify all my individual source files into one javaScript main.js file.
I'd like to know if the main.js file that I'm running in the browser was generated from a development build using webpack or a production build. How can I do this?
For example, in the webpack development config I do:
new webpack.DefinePlugin( {
IS_DEBUG_MODE: JSON.stringify( true ),
} ),
How can the compiled main.js file use this information to:
console.log( 'isDebugMode', ?? );
I tried doing process.env.IS_DEBUG_MODE but the browser gives me an error stating that process is not defined.
Figured out that I can use the html-webpack-plugin with template parameters to pass information from webpack into html.
https://github.com/jantimon/html-webpack-plugin/tree/main/examples/template-parameters

Configure Babel to include sibling modules referenced by alias into compilation

I have the following file structure:
application1
|pacakge.json
|src
||file1.ts
widget-lib
|package.json
|src
||file2.ts
||index.ts
.\widget-lib\src\index.ts bundles and reexports everything in widget-lib package.
export * from '.\file2'
.\application1\src\file1.ts and other files refence widget-lib by alias
import { foo } from 'widget-lib';
I'm compiling .\application1\src\ with Babel into .\application1\build-test\, how do I instruct Babel to also include widget-lib into this particular compilation? My goal is to produce a folder with all JS files needed to debug unit tests in modern node with esm package - just strip down TS types and put resulting JS files into proper place, like this:
application1
|build-test
||application1
|||src
||||file1.js
||widget-lib
|||src
||||index.js
||||file2.js
I'm using https://github.com/tleunen/babel-plugin-module-resolver to rewrite alias paths like 'widget-lib' to expected relative paths, I just need to instruct babel to also include the actual files from widget-lib into .\build-test\widget-lib folder. I tried passing both .\application1\src and .\widget-lib\src together to Babel, but than it outputs content of both .\src folders into one.
I ended up running several babel process in parallel, spawning them with a node script as described here Execute a command line binary with Node.js and using the script to analyze their output and emit additional information.

Nodejs - obfuscate entire project - gulp-javascript-obfuscator

I am new to Nodejs and I have a Nodejs project with around 80 JS files distributed in different sub-directories and some of the js files are reused in the project. I would like to obfuscate the code as this project is shipped and installed on client systems where I do not have control and anyone who has access to the client can see the code.
Currently I am using gulp node-module to build a tar file of my project artifact. I came across posts which talks about javascript obfuscation using node-modules: javascript-obfuscator and gulp-javascript-obfuscator. The examples I have seen is for a single file obfuscation but not for an entire nodejs project.
I see a snippet on javascript-obfuscator npm page about obfuscating entire directory:
javascript-obfuscator ./dist --output ./dist/obfuscated [options]
// creates a folder structure with obfuscated files under ./dist/obfuscated path
I would like to use the gulp-javascript-obfuscator node-module to obfuscate my entire project. It would be great if one of you can guide me or post a snippet of Gulp task which can do this.
On a different note: If one of my js file is importing another file with require(mycode-api) then after the obfuscation does this change to require(mycode-api-obfuscated).
Ref:
https://www.npmjs.com/package/javascript-obfuscator
https://github.com/javascript-obfuscator/gulp-javascript-obfuscator
To obfuscate entire project, try this:
gulp.src(['src/**/*.js'])
.pipe(javascriptObfuscator())
.pipe(gulp.dest('../dist'));
var gulp = require('gulp');
var pipelines = require('readable-stream').pipeline;
const javascriptObfuscator = require('gulp-javascript-obfuscator');
gulp.task('min-js', function () {
return pipelines(
gulp.src('js/*.js'),
javascriptObfuscator(),
gulp.dest('dist')
);
});

How to manage configuration for Webpack/Electron app?

I am using Webpack 2 and Electron to build nodejs application on Mac.
In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)
After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath()); to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]
path.join(remote.app.getAppPath(), 'data/tests/groups.json'); called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.‌​app/Contents/Resourc‌​es/default_app.asar. So it seems that the whole data folder is not picked up by webpacker.
Webpack config is using json-loader and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.
What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?
My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue
The Webpack Misconception
One thing to understand upfront is that webpack does not bundle files required through fs or other modules that ask for a path to a file. These type of assets are commonly labeled as Static Assets, as they are not bundled in any way. webpack will only bundle files that are required or imported (ES6). Furthermore, depending on your webpack configuration, your project root may not always match what is output within your production builds.
Based on the electron-vue documentation's Project Structure/File Tree, you will find that only webpack bundles and the static/ directory are made available in production builds. electron-vue also has a handy __static global variable that can provide a path to that static/ folder within both development and production. You can use this variable similar to how one would with __dirname and path.join to access your JSON files, or really any files.
A Solution to Static Assets
It seems the current version of the electron-vue boilerplate already has this solved for you, but I'm going to describe how this is setup with webpack as it can apply to not only JSON files and how it can also apply for any webpack + electron setup. The following solution assumes your webpack build outputs to a separate folder, which we'll use dist/ in this case, assumes your webpack configuration is located in your project's root directory, and assumes process.env.NODE_ENV is set to development during development.
The static/ directory
During development we need a place to store our static assets, so let's place them in a directory called static/. Here we can put files, such as JSONs, that we know we will need to read with fs or some other module that requires a full path to the file.
Now we need to make that static/ assets directory available in production builds.
But webpack isn't handling this folder at all, what can we do?
Let's use the simple copy-webpack-plugin. Within our webpack configuration file we can add this plugin when building for production and configure it to copy the static/ folder into our dist/ folder.
new CopyWebpackPlugin([
{
from: path.join(__dirname, '/static'),
to: path.join(__dirname, '/dist/static'),
ignore: ['.*']
}
])
Okay so the assets are in production, but how do I get a path to this folder in both development and production?
Creating a global __static variable
What's the point of making this __static variable?
Using __dirname is not reliable in webpack + electron setups. During development __dirname could be in reference to a directory that exists in your src/ files. In production, since webpack bundles our src/ files into one script, that path you formed to get to static/ doesn't exist anymore. Furthermore, those files you put inside src/ that were not required or imported never make it to your production build.
When handling the project structure differences from development and production, trying to get a path to static/ will be highly annoying during development having to always check your process.env.NODE_ENV.
So let's simplify this by creating one source of truth.
Using the webpack.DefinePlugin we can set our __static variable only in development to yield a path that points to <projectRoot>/static/. Depending if you have multiple webpack configurations, you can apply this for both a main and renderer process configuration.
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '/static').replace(/\\/g, '\\\\')}"`
})
In production, we need to set the __static variable manually in our code. Here's what we can do...
index.html (renderer process)
<!-- Set `__static` path to static files in production -->
<script>
if (process.env.NODE_ENV !== 'development') window.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
</script>
<!-- import webpack bundle -->
main.js (main process)
// Set `__static` path to static files in production
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
// rest of application code below
Now start using your __static variable
Let's say we have a simple JSON file we need to read with fs, here's what we can accomplish now...
static/someFile.json
{"foo":"bar"}
someScript.js (renderer or main process)
import fs from 'fs'
import path from 'path'
const someFile = fs.readFileSync(path.join(__static, '/someFile.json'), 'utf8')
console.log(JSON.parse(someFile))
// => { foo: bar }
Conclusion
webpack was made to bundle assets together that are required or imported into one nice bundle. Assets referenced with fs or other modules that need a file path are considered Static Assets, and webpack does not directly handle these. Using copy-webpack-plugin and webpack.DefinePlugin we can setup a reliable __static variable that yields a path to our static/ assets directory in both development and production.
To end, I personally haven't seen any other webpack + electron boilerplates handle this situation as it isn't a very common situation, but I think we can all agree that having one source of truth to a static assets directory is a wonderful approach to alleviate developer fatigue.
I think the confusion, (if there is any), might come from the fact that webpack not only "packs", embeds, things, code, etc... but also process content with its plugins.
html plugin being a good example, as it simply generates an html file at build-time.
And how this relates to the config file issue?,
well depending on how you are "requiring" the "config" file, what plug-in you are using to process that content.
You could be embedding it, or simply loading it as text, from file system or http, or else...
In the case of a config file, that I guess you want it to be parsed at runtime,
otherwise it's just fancy hardcoding values that perhaps you could be better simply typing it in your source code as simple objects.
And again in that case I think webpack adds little to nothing to the runtime needs, as there is nothing to pre-pack to read at later use,
so I would possibly instead or "require"it, i'll read it from the file system, with something like :
// read it parse it relative to appPath/cwd,
const config = JSON.parse(
fs.readfileSync(
path.join( app.getAppPath(), "config.json" ),
"utf-8"
))
//note: look fs-extra, it does all that minus the app.path plus async
and electron will read it from the file system , or if using Electron.require will read it from asar|fileSystem (in that order if I remember correctly, I could be wrong),
Webpack design philosophy is focused around very simple yet powerful concept:
Transform and bundle everything that is actually used by your app.
To achieve that webpack introduces a powerful concept of dependency graph, which is able to manage virtually any kind of dependencies (not only *.js modules) by the means of so-called loaders.
The purpose of a loader is to transform your dependency in a way that makes statement import smth from 'your_dependency' meaningful. For instance, json-loader calls JSON.parse(...) during loading of *.json file and returns configuration object. Therefore, in order to take advantage of webpack dependency resolution system for managing JSONs, start from installing json-loader:
$ npm install --save-dev json-loader
Then modify your webpack.config.js in the following way:
module.exports = {
...
module: {
rules: [
{test: /\.json$/, use: 'json-loader'}
]
}
...
};
At this point webpack should be able to resolve your JSON dependencies by their absolute paths, so the following should work (I assume here that you have a subdirectory config of your root context dir, containing file sample.json):
import sampleCfg from './config/sample.json';
But importing physical paths doesn't lead to elegant, robust and maintainable code (think of testability, for example), so it is considered a good practice to add aliases to your webpack.config.js for abstracting away your physical .config/ folder from your import statements
module.exports = {
...
resolve: {
alias: {
cfg: './config'
}
}
...
}
Then you'll be able to import your JSON config like that:
import sampleCfg from 'cfg/sample.json'
Finally, if you use SimulatedGREG/electron-vue Electron project template (as you mentioned in your post), then you have three webpack configuration files:
.electron-vue/webpack.web.config.js - use this config file if you use this template just for ordinary web development (i.e. not for building native Electron projects);
.electron-vue/webpack.main.config.js - use this file to configure webpack module that will run inside Electron's main process;
.electron-vue/webpack.renderer.config.js - use this file for Electron's renderer process.
You can find more information on main and renderer processes in the official Electron documentation.

Is there a way to lazily set the path of a resource with RequireJS?

So, I have an app that is using requireJS. Quite happily. For the most part.
This app makes use of Socket.IO. Socket.IO is being provided by nodejs, and does not run on the same port as the main webserver.
To deal with this, in our main js file, we do something like this:
var hostname = window.location.hostname;
var socketIoPath = "http://" + hostname + ":3000/socket.io/socket.io";
requirejs.config({
baseUrl: "/",
paths: {
app : "scripts/appapp",
"socket.io" : socketIoPath
}
});
More complicated than this, but you get the gist.
Now, in interactive mode, this works swimingly.
The ugliness starts when we try to use r.js to compile this (technically we're using grunt to run r.js, but that's besides the point).
In the config for r.js, we set an empty path for socket.io (to avoid it failing to pull in), and we set our main file as the mainConfigFile.
The compiler yells about this, saying:
Running "requirejs:dist" (requirejs) task
>> Error: Error: The config in mainConfigFile /…/client.js cannot be used because it cannot be evaluated correctly while running in the optimizer. Try only using a config that is also valid JSON, or do not use mainConfigFile and instead copy the config values needed into a build file or command line arguments given to the optimizer.
>> at Function.build.createConfig (/…/r.js:23636:23)
Now, near as I can figure, this is due to the fact that I'm using a variable to set the path for "socket.io". If i take this out, require runs great, but i can't run the raw from a server. If I leave it is, my debug server is happy, but the build breaks.
Is there a way that I can lazily assign the path of "socket.io" at runtime so that it doesn't have to go into the requirejs.config() methos at that point?
Edit: Did some extensive research on this. Here are the results.
Loading from CDN with RequireJS is possible with a build. However, if you're using the smaller Almond loader, it's not possible.
This leaves you with two options:
Use almond along with a local copy of the file in your build.
Use the full require.js loader and try to use a CDN.
Use a <script> tag just for that resource.
I say try for #2 because there are some caveats. You'll need to include require.js in your HTML with the data-main attribute for your built file. But if you do this, require and define will be global functions, allowing users to require any of your internal modules and mess around with them. If you're okay with this, you'll need to follow the "empty: scheme" in your build config (but not in your main config).
But the fact remains that you now have another HTTP request. If you only want one built file, which includes the require.js loader, you'll need to optimize for only one file.
Now, if you want to avoid users being able to require your modules, you'll have to do something like wrap:true in your build. But as far as I can tell, once your module comes down from CDN, if it's AMD, it's going to look for a global define function to register itself with, and that won't exist because it's now wrapped in a closure.
The lesson I took away from all this: inline your resources to your build. It makes sense. You reduce HTTP requests, minify it all and get gzip compression. You don't expose your modules to the world and everything is a lot simpler. If you cache your resources properly you won't even need to worry about it.
But since new versions of socket.io don't like AMD, here's how I did it. Make sure to include the socket.io <script> tag before requirejs. Then create a requirejs module named socket.io with the following contents:
define([], function () {
var io = window.io;
window.io = null;
return io;
});
Set the path like so: 'socket.io': 'core/socket.io' or wherever you want.
And require it as normal! The build works fine this way.
Original answer
Is it possible that you could make use of the path config fallbacks specified in the RequireJS API? Maybe you could save the file locally as a fallback so your build will work.
The socket.io GitHub repository specifies that you can serve the client with the files in the socket.io-client package's dist/ directory.

Categories

Resources