How can I avoid the creation of global functions when compiling typescript into javascript.
Benefit: obfuscator won't have to provide a public API
Foo.ts:
class Foo {}
Foo.js:
var Foo = (function () {
function Foo() {
}
return Foo;
}());
Foo.obfuscated.js (using npm jsobfuscator):
var _0xcd14=[];var _0x12e2=[];var Foo=(function(){function Foo(){}return Foo}())
Foo is still visible. I understand why (public API). Solution would be:
Foo.isolated.js:
(function() { /* code from Foo.js */ })();
Foo.isolated.obfuscated.js (what I want):
var _0xe1f1=[];var _0xa6a8=[];(function(){var _0x64f8x2=(function(){function _0x64f8x2(){}return _0x64f8x2}())})()
Is there a typescript setup for tsconfig.js / compiler options like isolation: true or something?
Wrapping the class inside a function scope should do the trick.
(function(){
class Foo {}
})
There isn't built in support in the form of an option as far as I am aware. Let me know if doing the above does not achieve your aim - in which case some more details about exactly what the goal is will help us understand what you're going for here.
nested (private) class ?
module MyModule {
export class MyPublicClass {
private myPrivateClass: PrivateClass;
constructor() {
this.myPrivateClass = new PrivateClass;
}
public test() {
this.myPrivateClass.test();
}
}
class PrivateClass {
public test() {
console.log('it works');
}
}
}
Related
I want to use Kotlin to generate some JavaScript like following:
function MyComponent() {
self.constructor = function() {}
}
The problem is constructor is a keyword in Kotlin, I can't just write like:
class MyComponent {
fun constructor() {}
}
I also tried:
class MyComponent {
#JsName("constructor")
fun ctor() {}
}
It still report errors like:
JavaScript name generated for this declaration clashes
with built-in declaration {1}
How to generate a javascript function which has name constructor?
There should be no problem with the top-level functions. The fun constructor() {} should just work, yielding function constructor(){}. At least that's what it does in Kotlin 1.2.31.
On the other hand member functions named constructor are prohibited (e.g. you cannot get A.prototype.constructor = function () {} in the output js file). For one thing that would ruin the is-check implementation.
Modifying the constructor property inside the class constructor should be possible:
// Kotlin
class A {
init{
this.asDynamic().constructor = fun(a: Int) { println(a) }
}
}
// JS
function A() {
this.constructor = A_init$lambda;
}
function A_init$lambda(a) {
println(a);
}
Hope that helped.
What is the perpose of calling privateMethod from the publicMethod?
Can't we just define the content of privateMethod inside the public method and do the same thing ?
var basketModule = (function() {
var basket = [];
function privateMethod() {
console.log(basket);
}
return {
publicMethod: function(){
privateMethod();
}
};
})());
basketModule.publicMethod();
In your simple example, there is not really a reason for privateMethod to exist because all publicMethod does is call it, but in a more real-world example, the private methods would do things that you don't want other modules calling on their own.
For example, this is a snippet of code that I worked on today, reduced to make it a good example:
(function(){
function _renderTreeLevel() { ... }
function _backfillAllSelectedStates() { ... }
function _updateSelectedCount() { ... }
return {
render: function() {
var expandCollapse = new ExpandCollapse();
expandCollapse.render();
_renderTreeLevel(0, this.ui.treeRegion, this.treeData);
_backfillAllSelectedStates();
_updateSelectedCount((this.options.selected || []).length);
$('.collapse').collapse();
}
};
})();
The 3 "private" function that start with '_' are just functions that I put code into for refactoring and making the code cleaner and more reusable. They are not functions that I want someone to be able to call.
Users of this module should call render() only.
The reasoning is the same as any other language that has public and private members built-in, like C# or Java, but since JavaScript doesn't provide that concept, this is the pattern that people follow to provide a similar behavior.
This is a follow-up question to In Node.js, how do I "include" functions from my other files?
I would like to include an external js file that contains common functions for a node.js app.
From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;
module.exports = 'all functions';
It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.
If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.
You can write all your function declarations first and then export them in an object:
function bar() {
//bar
}
function foo() {
//foo
}
module.exports = {
foo, bar
};
There's no magical one-liner though, you need to explicitly export the functions you want to be public.
I have done something like the following:
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
I require it in another file and I can access those functions
var Export = require('path/to/Exported');
Export.someFunction();
This is essentially just an object with functions in it, and then you export the object.
A really old question but I just had to solve the same issue myself.
the solution I used was to define a Class inside the module to contain all my functions and simply export an instance of the class.
classes.js looks like this:
class TestClass
{
Function1() {
return "Function1";
}
Function2() {
return "Function2";
}
}
module.exports = new TestClass();
app.js looks like this:
const TestClass = require("./classes");
console.log( TestClass.Function1);
just keep adding more functions to the class and they will be exported :)
It is worth noting that in ES6, you can now export functions like this:
export function foo(){}
export function bar(){}
function zemba(){}
Simply write export before the functions you want to export. More information here.
If you use ES6 you can do something like that:
function bar() {
//bar
}
function foo() {
//foo
}
export default { bar, foo };
const fs = require("fs")
var ExportAll = {
deleteFile : function deleteFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
fs.unlinkSync(imagePath)
}
},
checkFile : function checkFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
return true
}
else{
return false
}
},
rand : function(min=1,max=10)
{
return Math.floor((Math.random() * max) + min)
}
}
module.exports = ExportAll
Import everything from a type module file that has functions that are exported.
Found here:
https://javascript.info/import-export
myfile.js
export function myFunction()
{
// ................
}
export function myFunction2()
{
// ................
}
myfile2.js - import everything that is exported in the file
import * as myFunctions from './myfile.js';
// Usage
myFunctions.myFunction();
myFunctions.myFunction2();
I want to convert some JavaScript code I've written into TypeScript. I'm rather new to TypeScript syntax and way of thinking, as a JavaScript developer.
What is giving me a headache is the hard time I've had to convert some piece of code that uses the Revealing Module Pattern into TypeScript.
One example is the below:
//JS Code
var obj;
//code...
(function(){
function myFunction(){
//do work
}
function MyOtherConstructor(){
return {
publicMethod: myFunction
}
}
obj = new MyOtherConstructor();
})();
//use obj.publicMethod in code later
One workaround I've thought was this:
//TypeScript code
var obj;
class MyOtherConstructor {
private callback: any;
constructor(f: any){
this.callback = f;
}
publicMethod(): any{
this.callback();
}
}
//code...
(() => {
function myFunction(){
//do work
console.log("Called myFunction");
}
obj = new MyOtherConstructor(myFunction);
})();
//use obj.publicMethod in code later
which works, but it's ugly.
Any suggestion how make this better?
If you need a single object obj, then do not use a class. A namespace is more adapted:
namespace obj {
function myFunction() {
// ...
}
export var publicMethod = myFunction;
}
If you prefer to keep the class, then here is a more concise code for it:
class MyOtherConstructor {
constructor(public publicMethod: () => void) {
}
}
I'm currently writing some tests for a nodejs application.
assume that I have a module like this:
module.exports = function myModule(moduleParam) {
var someVar;
....
....
function helper(param) {
return param + someVar;
}
return {
doSomething: function (bar) {
....
....
var foo = helper(bar);
....
....
}
};
};
Assume that the 'helper' function is useful only within the module and should not be exposed to the outside.
What is the 'best practice' for testing it? (of course, I can test the doSomething function as a whole,but this way, the 'helper' function is tested in a particular situation, in a 'black-box' fashion).
I'm using nodeunit as testing framework, for that metter, but I can change it on need.
You don't test it. Unit testing is black box testing. This means that the only thing you test is the public interface aka contract.
Private functions such as these only can happen from refactoring public ones.
So if you consequently use TDD your private functions are implicitly tested.
If this feels wrong it's most often because your structure is wrong. Then you should think about moving your private stuff to an extra module.
Since i find tests to be a useful tool beyond unit testing and TDD (this SO answer makes a good argument), I made an npm package to help in cases like yours: require-from.
In you example this is how you would use it:
module-file.js:
function helper(param) {
return param + someVar;
}
module.exports = function myModule(moduleParam) {
var someVar;
....
....
return {
doSomething: function (bar) {
....
....
var foo = helper(bar);
....
....
}
};
};
module.helperExports = helper;
importing-file.js:
var requireFrom = require('require-from');
var helper = requireFrom('helperExports', './module-file'));
var public = requireFrom('exports', './module-file')); // same as require('./module-file')