Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Roadie
Jun 30, 2013

IAmKale posted:

So here's my question: How can I break up and organize my code into multiple files, but get tsc to output a single JavaScript file in basic ES5?

Use Webpack.

Adbot
ADBOT LOVES YOU

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Roadie posted:

Use Webpack.

and Babel

Roadie
Jun 30, 2013

Grump posted:

and Babel

You don't need Babel if it's an all-Typescript project. Just set the tsconfig.json to target ES5.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



ROFLburger posted:

That's been my experience too, and it certainly seems like it's more common with JS libraries than anything else I've worked with

If they take the time to write documentation they'll just get upstaged by the flavor of next month!

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Skandranon posted:

You can use TypeScript internal namespaces to manage the code across multiple files, and then do a simple concatenation of all the files. I usually use gulp-typescript and gulp-concat to do this, but you might be able to get tsc to do it by itself. PM me for a specific example if you need one.
Ah, internal namespaces and concatenation. I'll take a look at that and PM you if I end up banging my head against a wall.

Roadie posted:

Use Webpack.
I'm hoping to make this work using only the TypeScript executable because Webpack is haaaard :qq:

icantfindaname
Jul 1, 2008


Munkeymon posted:

I'm not sure what you mean by that, but I think you just need to add btnDownload.x and btnDownload.y to the form data like so

JavaScript code:
formRequest.data.append("btnDownload.x", 10);
formRequest.data.append("btnDownload.y", 10);
this.download //etc
Because that seems to be the difference between getting the HTML and CSV results when I gently caress with the POST parameters.

Really not sure how Phantom's support for attachment content-disposition is still so loving bad :\

E: I should probably explain that I figured that out by clicking the download button and looking at the request in Chrome's dev tools, then comparing the POST parameters in that request to the ones sent when the results load. Difference was the btnDownload ones. Confirmed by pasting the ones that trigger CSV results into Postman and deleting btnDownload

That still doesn't work. If I try to append the data outside the formRequest definition it gives me an error, if I do it within the definition it gives me the HTML again

This gives me an error

code:
				var formRequest = this.page.evaluate(function() {
					var formDom = document.forms["Form1"];
					
					return {
						action: formDom.action, 
						data: new FormData(formDom)
					};
				});
				
				formRequest.data.append("btnDownload.x", 10);
				formRequest.data.append("btnDownload.y", 10);

				this.download(formRequest.action, "industry.csv", "POST", formRequest.data);
code:
Test file: file.js
# Resurrectio test
FAIL TypeError: Object is not a constructor (evaluating 'formRequest.data.append("btnDownload.x", 10)')
#    type: uncaughtError
#    file: file.js:72
#    error: Object is not a constructor (evaluating 'formRequest.data.append("btnDownload.x", 10)')
#           phantomjs://code/file.js:72:28
#           runStep@phantomjs://platform/casper.js:1685:31
#           checkStep@phantomjs://platform/casper.js:414:28
#    stack: not provided
PASS Resurrectio test
FAIL 1 test executed in 3.476s, 0 passed, 1 failed, 0 dubious, 0 skipped.

Details for the 1 failed test:

In file.js:72
  Resurrectio test
    uncaughtError: TypeError: Object is not a constructor (evaluating 'formRequest.data.append("btnDownload.x", 10)')
This runs but gives me the HTML

code:
				var formRequest = this.page.evaluate(function() {
					var formDom = document.forms["Form1"];
					
					var a = formDom.action;
					var b = new FormData(formDom);
					
					b.append("btnDownload.x", 10);
					b.append("btnDownload.y", 10);
					
					return {
						action: a, 
						data: b
					};
				});

				this.download(formRequest.action, "industry.csv", "POST", formRequest.data);

icantfindaname fucked around with this message at 21:02 on Jul 10, 2017

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

IAmKale posted:

So here's my question: How can I break up and organize my code into multiple files, but get tsc to output a single JavaScript file in basic ES5?

This has become a more complicated question after TypeScript developers found out that people were using TypeScript wrong, so they fixed it and you can't really do this with TypeScript alone anymore. They would say that concatenating the files is wrong too.

The simplest and best solution:

Emit "es2015" targeted at "es5" compatibility. This will give you a folder full of your ts files, as es5 files, with es2015 import statements. Then use Rollup because Webpack is the worst thing to have ever happened. Rollup is really small, it will watch, and it will properly output a single file for you.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



icantfindaname posted:

That still doesn't work. If I try to append the data outside the formRequest definition it gives me an error, if I do it within the definition it gives me the HTML again

snip

This runs but gives me the HTML

code:
				var formRequest = this.page.evaluate(function() {
					var formDom = document.forms["Form1"];
					
					var a = formDom.action;
					var b = new FormData(formDom);
					
					b.append("btnDownload.x", 10);
					b.append("btnDownload.y", 10);
					
					return {
						action: a, 
						data: b
					};
				});

				this.download(formRequest.action, "industry.csv", "POST", formRequest.data);

I bet the FormRequest isn't serializing back out to the Phantom context :doh:

OK, I think we can skip the whole eval thing and use http://docs.casperjs.org/en/latest/modules/casper.html#getformvalues like this

JavaScript code:
var formData = this.page.getFormValues('#Form1');
formData['btnDownload.x'] = 10;
formData['btnDownload.y'] = 10;
this.download(this.getElementAttribute('#Form1', 'action'), 'industry.csv', "POST", fromData);

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

IAmKale posted:

Ah, internal namespaces and concatenation. I'll take a look at that and PM you if I end up banging my head against a wall.

I'm hoping to make this work using only the TypeScript executable because Webpack is haaaard :qq:

Spend an hour or two dedicated to learning webpack. Its easy after that. Here's a copy/paste of the webpack config from the webpack-bundled react typescript project I'm working on right now.

code:
const path = require('path');

module.exports = {
  entry: {
    application: './path/to/your/index.tsx',
  },
  output: {
    // wherever you want your output
    path: path.join(__dirname, 'static'),
    filename: 'bundle.js',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  devtool: 'source-map',
  module: {
    rules: [
      // changed from { test: /\.jsx?$/, use: { loader: 'babel-loader' } },
      { test: /\.([tj])sx?$/, use: { loader: 'awesome-typescript-loader' } },
      // addition - add source-map support
      { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  watch: true,
};

necrotic
Aug 2, 2005
I owe my brother big time for this!

huhu posted:

code:
var list = ["a", "b"];
for (var item in list) {
    var postData = {
	item: item
    };

console.log(postData[item]);

    genAjaxPost(postData,
        "/dest/place",
        "",
        function (data) {
            console.log(postData[item]);
        })
};
The result of console.log() is:

code:
"a"
"b"
"b"
"b"
There are definitely some syntax errors in this JS. Why is the for loop running twice to get the two items "a" and "b" but the Ajax post only gets "b" twice?

In addition to the already posted you could replace the "for" loop with "list.forEach" to get the same effect as the given solution:

code:
list.forEach(f); // Where f is the function defined in the other solution

icantfindaname
Jul 1, 2008


Munkeymon posted:

I bet the FormRequest isn't serializing back out to the Phantom context :doh:

OK, I think we can skip the whole eval thing and use http://docs.casperjs.org/en/latest/modules/casper.html#getformvalues like this

JavaScript code:
var formData = this.page.getFormValues('#Form1');
formData['btnDownload.x'] = 10;
formData['btnDownload.y'] = 10;
this.download(this.getElementAttribute('#Form1', 'action'), 'industry.csv', "POST", fromData);

Okay, it worked. Thanks!

Dominoes
Sep 20, 2007

IAmKale posted:

So here's my question: How can I break up and organize my code into multiple files, but get tsc to output a single JavaScript file in basic ES5?
Webpack; I can show you a working config if you want. This official guide is labeled 'React', but isn't specific to it; it solves your problem. I wish Typescript could handle this so we could skip Webpack and let TS handle everything, but this isn't the case currently.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Honest Thief posted:

Maybe this is just me bitching and being annoying but it seems every other article about some new js tool barely covers the basic use cases. Case in point, I'm trying to figure out the syntax it accepts for custom routing, only the given example on the repo doesn't work, and none of the article I can find seem to consider the possibility of wanting to have custom routes.
edit:Ok, fine, it uses path-to-regexp, but some headsup would be nice

Yeah, that's javascript.

Even seemingly well documented frameworks either document a function superficially*, or there have been breaking changes in the api in minor versions and nobody bothered to update the documentation/tutorials.

*)something like "the function takes a configuration object and a callback" without telling the structure of the object or the parameters the callback will be called with

Honest Thief
Jan 11, 2009
Maybe this is all nostalgia or something but I seem to recall this not being the case 4, 5 years ago, or at least not the norm. Although I bet it's related to how everyone started making frameworks or whatever in order to pump up their notoriety.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Wheany posted:

there have been breaking changes in the api in minor versions and nobody bothered to update the documentation/tutorials.

the node community has a hard-on for semantic versioning but NEVER gets it right. I cannot count how many times the default npm install mode of pinning to the major version not actual mattering at all and entire projects breaking from a minor release.

Honest Thief posted:

Maybe this is all nostalgia or something but I seem to recall this not being the case 4, 5 years ago, or at least not the norm. Although I bet it's related to how everyone started making frameworks or whatever in order to pump up their notoriety.

I blame npm and the node community in general for a shitload of the issues.

How many package managers do you know with a huge staff, multi-hundred million dollar valuation and funding? NPM is the only one I'm aware of!

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Thank you all for pointing me back towards Webpack and the React/TypeScript tutorial. I was able to produce the desired output by emitting es2015 modules targeting ES5, then bundling those using awesome-typescript-loader via Webpack. It even made it painless to incorporate polyfills for window.fetch() and Promises without having to add anything to my TypeScript files, just a couple of strings to the Webpack config's entry array :woop:

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

IAmKale posted:

Thank you all for pointing me back towards Webpack and the React/TypeScript tutorial. I was able to produce the desired output by emitting es2015 modules targeting ES5, then bundling those using awesome-typescript-loader via Webpack. It even made it painless to incorporate polyfills for window.fetch() and Promises without having to add anything to my TypeScript files, just a couple of strings to the Webpack config's entry array :woop:

Webpack is pretty awesome if you can get past the initial hump. Even if typescript supported bundling, I'd still use webpack. It brings too many other useful features to the table.

necrotic
Aug 2, 2005
I owe my brother big time for this!
webpack is cool as long as they stop completely rewriting it every major version.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

necrotic posted:

webpack is cool as long as they stop completely rewriting it every major version.

Well, they didnt do that for 2 -> 3...

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!
But with HTTP2 you don't need to concatenate so Webpack is useless now.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

The Merkinman posted:

But with HTTP2 you don't need to concatenate so Webpack is useless now.

Looking forward to using HTTP2 in 2027

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Wheany posted:

Looking forward to using HTTP2 in 2027

Support is already pretty good http://caniuse.com/#search=http2

necrotic
Aug 2, 2005
I owe my brother big time for this!

The Merkinman posted:

But with HTTP2 you don't need to concatenate so Webpack is useless now.

It's my understanding you don't want to be sending a lot of small files, even with HTTP/2. Some level of bundling is still a good idea, just not the current approach of "everything in one file".

At least in React land there's been a lot of work towards splitting large projects up into multiple bundles that lazily load when required. That seems like the right approach going forward, which still requires webpack or similar.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The Merkinman posted:

But with HTTP2 you don't need to concatenate so Webpack is useless now.

http://w4t.pw/5kcz

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

necrotic posted:

the node community has a hard-on for semantic versioning but NEVER gets it right. I cannot count how many times the default npm install mode of pinning to the major version not actual mattering at all and entire projects breaking from a minor release.

Yep, pin your dependencies kids, ^ cannot be trusted to give you a good time across machines/servers.

necrotic
Aug 2, 2005
I owe my brother big time for this!
It's just great that NPM defaults to the carrot. At least they have a package lock finally?

Kekekela
Oct 28, 2004

necrotic posted:

It's just great that NPM defaults to the carrot. At least they have a package lock finally?

I just always used 'npm shrinkwrap' before we switched to yarn.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Kekekela posted:

I just always used 'npm shrinkwrap' before we switched to yarn.

Yeah everyone should have been. The fact that it took them 5 major versions to make shrinkwrap-like behavior the default is indefensible, though.

LP0 ON FIRE
Jan 25, 2006

beep boop
I'm trying to add a style to YOSPOS, and for the life of me I can't remove the background image and color for the seen threads, though when I go into in inspector and disable them, it works.

code:
(function() {
    'use strict';
    window.onload = function() {
        $('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').css({
            'background-image': 'linear-gradient(to bottom, red 0%, blue 100%)',
            'background-origin': 'border-box',
            'border-spacing': '1px',
            'border': '1px solid transparent'
        });
        $('tr.seen, tr.seen1, tr.seen2').css({
            'background-color': 'rgba(0,0,0,0)',
            'background-image': 'none',
            'background-repeat':'none'
        });
    };
})();
What's the deal?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

necrotic posted:

Yeah everyone should have been. The fact that it took them 5 major versions to make shrinkwrap-like behavior the default is indefensible, though.

Except now the lockfile doesn't actually get updated when you change package.json, only when you run npm. This means you can't update things via package.json, as it will keep using your old lock file. So you just have to habitually delete the lock file (or disable it entirely), or update all packages 1 at a time via the command line.

Video Nasty
Jun 17, 2003

LP0 ON FIRE posted:

I'm trying to add a style to YOSPOS, and for the life of me I can't remove the background image and color for the seen threads, though when I go into in inspector and disable them, it works.

code:
(function() {
    'use strict';
    window.onload = function() {
        $('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').css({
            'background-image': 'linear-gradient(to bottom, red 0%, blue 100%)',
            'background-origin': 'border-box',
            'border-spacing': '1px',
            'border': '1px solid transparent'
        });
        $('tr.seen, tr.seen1, tr.seen2').css({
            'background-color': 'rgba(0,0,0,0)',
            'background-image': 'none',
            'background-repeat':'none'
        });
    };
})();
What's the deal?

Might be a race condition that you're executing when the window is ready but not the body of the DOM? Also, for fun you could throw an !important beside the `none` for background-image to enforce it above everything else.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Surprise: NPM is still bad!

necrotic
Aug 2, 2005
I owe my brother big time for this!

Video Nasty posted:

Might be a race condition that you're executing when the window is ready but not the body of the DOM? Also, for fun you could throw an !important beside the `none` for background-image to enforce it above everything else.

onload fires after _everything_ has loaded, so the DOM is definitely available.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Video Nasty posted:

Might be a race condition that you're executing when the window is ready but not the body of the DOM? Also, for fun you could throw an !important beside the `none` for background-image to enforce it above everything else.

You sure something else isn't also assigning something to window.onload?

necrotic
Aug 2, 2005
I owe my brother big time for this!
I actually took a look at that and there wasn't anything on it. Not a bad idea to try the addEventListener method a shot, the code definitely works.

porksmash
Sep 30, 2008
package-lock.json "describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates."

How come pulling down a repo and running npm i modifies package-lock.json? I develop on two different computers and it's driving me crazy. I'll add a package on my laptop, commit package.json and package-lock.json, and then when I pull the change and npm i, I get a different package-lock.json. Doesn't this defeat the purpose? Am I misunderstanding why package-lock.json exists?

geeves
Sep 16, 2004

LP0 ON FIRE posted:

I'm trying to add a style to YOSPOS, and for the life of me I can't remove the background image and color for the seen threads, though when I go into in inspector and disable them, it works.

What's the deal?
code:
(function() {
    'use strict';
    if (document.body.classList.contains("forum_219")) {
        window.addEventListener("load", function() {
            console.log("loaded now bastard child yospossing");
            $('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').css({
                'background-image': 'linear-gradient(to bottom, red 0%, blue 100%)',
                'background-origin': 'border-box',
                'border-spacing': '1px',
                'border': '1px solid transparent'
            });
            $('tr.seen, tr.seen1, tr.seen2').css({
                'background-color': 'rgba(0,0,0,0)',
                'background-image': 'none',
                'background-repeat':'none'
            });
        });
    }
}());
This style looks ugly as hell (but bold!) with tampermonkey, but change to window.addEventListener("load", function(){});



edit: sans jquery

code:
(function() {
    'use strict';
    if (document.body.classList.contains("forum_219") {
        window.addEventListener("load", function() {
        console.log("loaded now yospossing");
        document.querySelectorAll('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').forEach(function(el) {
            el.style.backgroundImage = 'linear-gradient(to bottom, red 0%, blue 100%)';
            el.style.backgroundOrigin = 'border-box';
            el.style.borderSpacing= '1px';
            el.style.border = '1px solid transparent';
        });
        document.querySelectorAll('tr.seen, tr.seen1, tr.seen2').forEach(function(el) {
            el.style.backgroundColor= 'rgba(0,0,0,0)';
            el.style.backgroundImage = 'none';
            el.style.backgroundRepeat = 'none';
        });
    }
    );
}
 }
 }());

geeves fucked around with this message at 03:07 on Jul 13, 2017

Roadie
Jun 30, 2013

porksmash posted:

How come pulling down a repo and running npm i modifies package-lock.json? I develop on two different computers and it's driving me crazy. I'll add a package on my laptop, commit package.json and package-lock.json, and then when I pull the change and npm i, I get a different package-lock.json. Doesn't this defeat the purpose? Am I misunderstanding why package-lock.json exists?

It sounds like you've got two different versions of npm 5.0.x. They're still fiddling with the fine details of the package-lock.json format.

LP0 ON FIRE
Jan 25, 2006

beep boop

Video Nasty posted:

Might be a race condition that you're executing when the window is ready but not the body of the DOM? Also, for fun you could throw an !important beside the `none` for background-image to enforce it above everything else.

Possibly, but I don't know what it is. !important didn't do anything.


geeves posted:

code:
(function() {
    'use strict';
    if (document.body.classList.contains("forum_219")) {
        window.addEventListener("load", function() {
            console.log("loaded now bastard child yospossing");
            $('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').css({
                'background-image': 'linear-gradient(to bottom, red 0%, blue 100%)',
                'background-origin': 'border-box',
                'border-spacing': '1px',
                'border': '1px solid transparent'
            });
            $('tr.seen, tr.seen1, tr.seen2').css({
                'background-color': 'rgba(0,0,0,0)',
                'background-image': 'none',
                'background-repeat':'none'
            });
        });
    }
}());
This style looks ugly as hell (but bold!) with tampermonkey, but change to window.addEventListener("load", function(){});



edit: sans jquery

code:
(function() {
    'use strict';
    if (document.body.classList.contains("forum_219") {
        window.addEventListener("load", function() {
        console.log("loaded now yospossing");
        document.querySelectorAll('div.threadbar.top, div.threadbar.bottom, div.forumbar, #forum, #filter').forEach(function(el) {
            el.style.backgroundImage = 'linear-gradient(to bottom, red 0%, blue 100%)';
            el.style.backgroundOrigin = 'border-box';
            el.style.borderSpacing= '1px';
            el.style.border = '1px solid transparent';
        });
        document.querySelectorAll('tr.seen, tr.seen1, tr.seen2').forEach(function(el) {
            el.style.backgroundColor= 'rgba(0,0,0,0)';
            el.style.backgroundImage = 'none';
            el.style.backgroundRepeat = 'none';
        });
    }
    );
}
 }
 }());


That screen shot is precisely what is happening with my original code too. I can't remove the background image and color for the seen threads, leaving that ugly green backgrounds there. Not too say that my style is not ugly.

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

LP0 ON FIRE posted:

That screen shot is precisely what is happening with my original code too. I can't remove the background image and color for the seen threads, leaving that ugly green backgrounds there. Not too say that my style is not ugly.

I made a change last night and forgot to edit it in.

Remove the 'seen" classes. It's the only way I could remove the background in the inspector.

code:
             document.querySelectorAll('tr.seen, tr.seen1, tr.seen2').forEach(function (el) {
                    el.classList.remove("seen");
                    el.classList.remove("seen1");
                    el.classList.remove("seen2");
                    el.style.backgroundColor = '#fff';
                    el.style.backgroundImage = 'none';
                    el.style.backgroundRepeat = 'none';
                });

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply