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
kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison

Joda posted:

I put them in global and link to projects. Is that bad?

As long as your package.json is correct I guess, but why?

Adbot
ADBOT LOVES YOU

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Joda posted:

I put them in global and link to projects. Is that bad?
How do you do that? I would rather do it that way, I just couldn't get it to work.

Munkeymon
Aug 14, 2003

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



roomforthetuna posted:

How do you do that? I would rather do it that way, I just couldn't get it to work.

You shouldn't if you're going to share your project with anyone

evilfunkyogi
Jun 27, 2005
:effort:
Or work on multiple projects that might need different versions of the same package.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

evilfunkyogi posted:

Or work on multiple projects that might need different versions of the same package.
I mentioned this system at work and someone asks the interesting question, what happens if you work on two projects where one depends on the other and they both depend on the same external dependency, but have different versions in their package file? Does npm just say "gently caress you, make these versions the same"? Do you end up with both versions in your target?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

roomforthetuna posted:

I mentioned this system at work and someone asks the interesting question, what happens if you work on two projects where one depends on the other and they both depend on the same external dependency, but have different versions in their package file? Does npm just say "gently caress you, make these versions the same"? Do you end up with both versions in your target?

Whenever you wonder how npm does something, think of the absolute stupidest way you could think of it being done: npm likely does something stupider.

Turtlicious
Sep 17, 2012

by Jeffrey of YOSPOS
e: There's an api i can just use, nvm.

Turtlicious fucked around with this message at 00:56 on Jul 31, 2018

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
I have a slider which, when changed is sending a server request. However I don't want to send a billion server requests everytime the slider is moved. What is the best way to only send a request after the slider has been moved and hasn't changed for say 1 second?

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

Knifegrab posted:

I have a slider which, when changed is sending a server request. However I don't want to send a billion server requests everytime the slider is moved. What is the best way to only send a request after the slider has been moved and hasn't changed for say 1 second?

https://css-tricks.com/debouncing-throttling-explained-examples/

Use debounce. Lodash has an implementation: https://lodash.com/docs/4.17.10#debounce

geeves
Sep 16, 2004

roomforthetuna posted:

I'm trying to get my head around the behavior of node_modules (with typescript).

It seems like the standard way of installing your module dependencies is "npm install whatever" in your project path, which makes a node_modules folder, which seems like ... a heap of crap. I don't want all the dependencies of a project in the same path as that project. But it seems that "npm install -g whatever" to install things in the global space doesn't make them available for imports?

What's the non-stupid way of doing this? I must be missing something. People do this with git, and surely don't have all their dependencies in their git repositories - do they just put node_modules in their .gitignore? If so, are the dependencies captured somewhere else so there's a record of what your module needs somewhere? Or are you supposed to set it up so you do npm install somewhere *above* your project path?

Everything I find saying how to do things just seems to manually mash the node_modules dependencies right into the middle of your project, surely that can't really be the way?

This is my main gripe with npm / node. "Hey let's look at what one of the most popular and successful library management tools did and ignore loving everything they did right because we want to re-imagine development."

loving idiots.

My gradle / .m2 repository 3g for all of my projects. All of my node_modules combined 15g :v:

edit: Bigger gripe is with package-lock.json. I don't know what it is, but it loving sucks. All devs are on the same image, same version of Node and same version of NPM. Every build package-lock.json gets conflicting changes added / checked in.

We switched to Yarn and this doesn't happen.

Even if everything was global, NPM does not version correctly at all. It means if I switch between branches and one branch has React 16.3 and the other has 16.4 that I'm testing, they constantly overwrite each other when I switch between them. WHY? Oh because while they're so big on semver they fail to implement it in a sane way for development.

geeves fucked around with this message at 02:49 on Aug 10, 2018

porksmash
Sep 30, 2008
I know it's different behavior than the old npm that didn't do lockfiles, but the docs explain exactly how npm functions and how to avoid/fix exactly what you're encountering: https://docs.npmjs.com/files/package-locks

Obfuscation
Jan 1, 2008
Good luck to you, I know you believe in hell
Am I expecting too much when I was hoping that VS Code would notify me about stupid small mistakes, like reassigning a const or using = instead of === inside an if? What's the best way to handle this:

-never do mistakes
-attach eslint to every single script separately
-install eslint globally and deal with that hassle?

Obfuscation fucked around with this message at 13:09 on Aug 10, 2018

smackfu
Jun 7, 2004

Use WebStorm?

Obfuscation
Jan 1, 2008
Good luck to you, I know you believe in hell

smackfu posted:

Use WebStorm?

But it costs money! I really like PyCharm though, so I'll check it out.

tracecomplete
Feb 26, 2017

Obfuscation posted:

Am I expecting too much when I was hoping that VS Code would notify me about stupid small mistakes, like reassigning a const or using = instead of === inside an if? What's the best way to handle this:

-never do mistakes
-attach eslint to every single script separately
-install eslint globally and deal with that hassle?

Put your scripts inside a package (everything can and should be packaged), put ESLint and your preferred directives in it.

Or use TypeScript like a sane person, the compiler will scream. Babel too I guess, but TypeScript is your friend.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Sometimes if you're code golfing, doing = instead of == in a conditional on purpose is a valid way to combine steps

Doom Mathematic
Sep 2, 2008

Obfuscation posted:

Am I expecting too much when I was hoping that VS Code would notify me about stupid small mistakes, like reassigning a const or using = instead of === inside an if? What's the best way to handle this:

-never do mistakes
-attach eslint to every single script separately
-install eslint globally and deal with that hassle?

Install eslint locally, set up a pre-testing step which runs the linter across all your scripts.

Dumb Lowtax posted:

Sometimes if you're code golfing, doing = instead of == in a conditional on purpose is a valid way to combine steps

Code golf is like the exact opposite of linting.

Doom Mathematic
Sep 2, 2008

geeves posted:

edit: Bigger gripe is with package-lock.json. I don't know what it is, but it loving sucks. All devs are on the same image, same version of Node and same version of NPM. Every build package-lock.json gets conflicting changes added / checked in.

Have you considered finding out what it is?

geeves
Sep 16, 2004

npm (tried every option with it command line) always made a change to package-lock.json

We swtiched to yarn. No more problem

Doom Mathematic
Sep 2, 2008

geeves posted:

Even if everything was global, NPM does not version correctly at all. It means if I switch between branches and one branch has React 16.3 and the other has 16.4 that I'm testing, they constantly overwrite each other when I switch between them.

This is kind of to be expected in any situation where you've checked in your dependencies and different branches use different dependencies. You could consider ignoring node_modules.

FSMC
Apr 27, 2003
I love to live this lie
I'm trying to get jest working with multiple functions. Apart from a basic example for one function I can't find anything that works well when I want to test multiple function in a file. I can get the tests to work if I export them in a certain way, but I don't understand how it works or what is going on in terms of exporting the functions and importing them. The var module isn't defined so while the test works, the actual file is invalid. If I define the module using module={};, then the jest test don't work. I've tried rewriting in pretty every other way I've seen but the tests don't work.


code:
//highlight.js
.....
module.exports = {};
module.exports.flattenObject = flattenObject;
module.exports.removePrefix = removePrefix;
module.exports.showIxbrlElements = showIxbrlElements;

//the test file
const mod = require('./highlight');

test('flatten simple one layer deep', () => {
    expect(JSON.stringify(mod.flattenObject({ "a": { "b": 1 } }))).toBe(JSON.stringify({ "a\nb": 1 }));
});

var ob = { "a": { "b": 1 }, "b": 2, "d": { "2": 3, "deep": { "d": 9 } } };
var fob = { "a\nb": 1, "b": 2, "d\n2": 3, "d\ndeep\nd": 9 };
test('complex ob flatten', () => {
    expect(JSON.stringify(mod.flattenObject(ob))).toBe(JSON.stringify(fob));
});

test('remove prefix from names', () => {
    expect(mod.removePrefix("ix:name")).toBe("name");
});

FSMC fucked around with this message at 00:30 on Aug 25, 2018

necrotic
Aug 2, 2005
I owe my brother big time for this!
module is a node file-scoped variable. Is your linter complaining or is it a runtime error? The module system in node (where the module var comes from) does not exist in browsers and needs a transpiler to work.

https://nodejs.org/api/modules.html

FSMC
Apr 27, 2003
I love to live this lie

necrotic posted:

module is a node file-scoped variable. Is your linter complaining or is it a runtime error? The module system in node (where the module var comes from) does not exist in browsers and needs a transpiler to work.

https://nodejs.org/api/modules.html

Thanks, that makes sense. The error was in the browser console. I added the following line which sorted it out.

code:
if (module == null) var module = {};

Doom Mathematic
Sep 2, 2008

FSMC posted:

Thanks, that makes sense. The error was in the browser console. I added the following line which sorted it out.

code:
if (module == null) var module = {};

Unfortunately, adding this line is probably not the correct solution...

The system of loading which uses module to export things from one source file and require to import them into another file is called "CommonJS". This works fine in an environment like Node.js which actually supports/implements CommonJS. A web browser, though, doesn't. Trying to access module or require in this context should cause an error, as you've seen.

Normally, to get CommonJS source files to work in a browser, you need to bundle them somehow, using a tool like webpack (or, historically, Browserify). The output from this bundling step will be a new single JavaScript file which bundles all your code together with implementations of module and require which do the right thing.

Those implementations have some subtlety to them. Your solution of manually creating a module variable if it doesn't already exist (and then, and I'm just guessing this part, just loading each raw source file one by one?) might work right now, but it's likely to stop working as soon as you have a third source file. Just something to bear in mind... It's worth figuring webpack out. It's a valuable skill.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
Also, if you hate bundled JS for potentially being a horrifying giant file most of which isn't used, there is dynamic importing, but it's significantly more of a pain.
(Dynamic importing, code splitting)

(I'm using this because I'm trying to make multiple minigames through one interface operating with persistent WebRTC connections - loading the minigames only on demand makes sense.)

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
Speaking of which, now I have a problem. (Or "you have a problem, so you decided to use webpack, now you have two problems.")

I'm trying to do a webpack config that can build two things. At the moment I've disabled one of them while I work on the other, but webpack keeps trying to build files it should have no reference to.
ie. with the following webpack.config.js I get
ERROR in [...]\client\somefile.ts
When as far as I can tell it shouldn't be looking in /client/ at all, no files in there are referenced by any of the files in /server/. What am I misunderstanding? It it just trying to build all ts files below the current path just in case I might want them at some point?

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

const serverConfig = {
    target: 'node',
    entry: './server/main.ts',
    mode: 'production',

    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js'
    },

    resolve: {
        extensions: ['.js', '.ts']
    },

    externals: ['ws'],
    module: {
        noParse: [/^ws$/],
        rules: [
            {
                test: /\.ts$/,
                include: [path.join(__dirname, 'server')],
                loader: 'ts-loader',
                options: { configFile: 'tsconfig.server.json' }
            }
        ]
    },
};

//module.exports = [serverConfig, clientConfig];
module.exports = [serverConfig];
Edit: just to be absolutely sure the files aren't referenced by anything I expect to be building I renamed somefile.ts to somefile2.ts, which provoked the same error but with somefile2.ts, so it's definitely not some stray reference.

roomforthetuna fucked around with this message at 21:05 on Aug 26, 2018

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
I found the answer to my own question - a missing option with a surprising default:
code:
module: {
  rules: [
    {
      loader: 'ts-loader',
      options {
        onlyCompileBundledFiles: true,
      }
    }
  ]
}

Khorne
May 1, 2002
What is the correct way to store global state on a page in vanilla javascript in the year 2018?

Khorne fucked around with this message at 16:52 on Aug 27, 2018

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Khorne posted:

What is the correct way to store global state on a page in vanilla javascript in the year 2018?

If you must, I would put it in a single object to sort of namespace it.

JavaScript code:
KHORNE_GLOBAL = {
   myThing: 1,
   otherThing: 'blah'
}
EDIT: and if you have multiple files that need to access it, make sure you check for it first so you don't over-write it.

Khorne
May 1, 2002

Lumpy posted:

If you must, I would put it in a single object to sort of namespace it.

JavaScript code:
KHORNE_GLOBAL = {
   myThing: 1,
   otherThing: 'blah'
}
EDIT: and if you have multiple files that need to access it, make sure you check for it first so you don't over-write it.
Thankfully it's an extremely simple 1 file case which is why I am doing this instead of just using vue or react. There are other reasons at play, and other people will have to maintain this, so I figured I'd ask a kinda dumb question.

I remember creating really complex SPAs in 2005 and boy was that not very fun.

I think the actual question was more about scope and lifetime of variables in a script tag, which is obvious when framed that way. I was confusing myself, and definitely forgot that setting a var under a script tag gets shoved into window.

edit: But "let" does not. A variable set with let is still accessible from the console, but it is not appended to window. Am I going to run into any scoping issues using let vs var in this case?

Khorne fucked around with this message at 17:03 on Aug 27, 2018

Doom Mathematic
Sep 2, 2008
I would be more inclined to explicitly use window.KHORNE_GLOBAL, a property on a variable window which you already know to be global.

prisoner of waffles
May 8, 2007

Ah! well a-day! what evil looks
Had I from old and young!
Instead of the cross, the fishmech
About my neck was hung.

Doom Mathematic posted:

I would be more inclined to explicitly use window.KHORNE_GLOBAL, a property on a variable window which you already know to be global.

:yossame:

geeves
Sep 16, 2004

Lumpy posted:

If you must, I would put it in a single object to sort of namespace it.

JavaScript code:
KHORNE_GLOBAL = {
   myThing: 1,
   otherThing: 'blah'
}
EDIT: and if you have multiple files that need to access it, make sure you check for it first so you don't over-write it.

Doom Mathematic posted:

I would be more inclined to explicitly use window.KHORNE_GLOBAL, a property on a variable window which you already know to be global.

I'm personally fond of using an IFFE to assign it to window.

https://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailnamespacing

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

roomforthetuna posted:

I found the answer to my own question - a missing option with a surprising default:
Also, similarly, webpack-node-externals is a thing you apparently want to do to stop typescript node targets from whining about all the dependencies not being quite typescripty enough in various ways.
These defaults loving suck, this build system loving sucks, and so do all the others, argh, I should have just used makefiles.

Edit: also tsconfig-paths-webpack-plugin sigh.
Edit2: vvvv Yeah, fair enough, getting the ONE external dependency I want to use to work with makefiles would probably have been as much hassle as all this stupid poo poo.

roomforthetuna fucked around with this message at 04:24 on Aug 29, 2018

qsvui
Aug 23, 2003
some crazy thing

roomforthetuna posted:

I should have just used makefiles.

no

FSMC
Apr 27, 2003
I love to live this lie
I'm writing a browser bookmarklet/extension and have just started using unit tests. This is the first time I've ever used a unit test and they are amazing especially since I'm still a js noob. I have jest tests working for half the functions. I've got my js working fine on a html page with just a minor formatting issue . But under the hood something is going serious wrong when it extracts data from the html page. So rather than regressing back to bad habits and manually digging through the logs trying to figure out what is gong on I want to use some automated tests. I want to automatically test the functions that extracts data from the html file. This is where I'm completely lost and don't even know if I want to do is a unit test or if it's some kind of integration test.

Here is an simple example of what I'm doing:
Open a saved copy of twitter.com.
Create a list of all the visible tweets by id. This is what i want to test but I don't know how to do this in Jest or if I actually need to use another framework
Match the tweet ids against a fixed list of ids. - working unit test
Highlight matched tweets green. - Would this be some kind of snapshot test?

I also think that the working unit tests are fruit of the poisonous tree and will break with real inputs. So I want to test things using html files as inputs, which I think it more of a integration test since it will test multiple functions.

Oh and if it matters I'm currently using vscode with jest.
Edit: Oh and if I need to use something else other than jest, can I just use that for all testing or I would I need to use both?

FSMC fucked around with this message at 23:34 on Sep 1, 2018

spiritual bypass
Feb 19, 2008

Grimey Drawer

FSMC posted:

I'm writing a browser bookmarklet/extension and have just started using unit tests.

Sounds like you've got a problem either selecting the right section of the document or parsing its contents?
You could include as part of a your tests a set of copy/pastes of input data that would normally come from the service you're scraping. This is sometimes called a "fixture." Add a couple consts or functions with a couple versions of passing and failing data as appropriate and then write and test the functions that parse it. Testing the fetch code could be harder, but if you've really separated the fetching logic from the parsing logic, there shouldn't be much room for error. I usually say skip the tests that interact with 3rd party services if the rest is solid.

Roadie
Jun 30, 2013

FSMC posted:

Create a list of all the visible tweets by id. This is what i want to test but I don't know how to do this in Jest or if I actually need to use another framework

Break down the code that does it into a standalone piece that just fetches the data and then something else that parses it, and for the fetch part use a mock of one kind or another that replaces the fetch or xhr call as part of the test, set up to return fake (but realistic) data. jest-fetch-mock is one example.

Roadie fucked around with this message at 02:41 on Sep 2, 2018

FSMC
Apr 27, 2003
I love to live this lie

Roadie posted:

Break down the code that does it into a standalone piece that just fetches the data and then something else that parses it, and for the fetch part use a mock of one kind or another that replaces the fetch or xhr call as part of the test, set up to return fake (but realistic) data. jest-fetch-mock is one example.

I have quite a few functions that go through the DOM, extracts bits and changes bits, so I want to test the key functionality of my code. It will be running over a variety of x/html files, some that use various standards, ignore standards and do things in completely different ways. I think my issue is there is no way I'll ever get anywhere near being able to write good mock functions to emulate these functions acting on these html files. Why can't I test the actual functions acting on a html file?

Here is an example where "nodes = document.body.getElementsByTagName(elementCases[j]);" is giving me result I wasn't expecting. I don't know how I would mock this or what a mock should output. It seems like there should be a way to tests my functions on a test html file.

code:
/**
 * Gets Ixbrl elements from doc
 */
function getIxbrlElements() {
    var elements = {};
    var value = {};

    for (var i = 0; i < IXBRL_ELEMENTS.length; i++) {
        elementCases = getCases(IXBRL_ELEMENTS[i]);
        value = {};
        for (var j = 0; j < elementCases.length; j++) {
            nodes = document.body.getElementsByTagName(elementCases[j]);
            for (var k = 0; k < nodes.length; k++) {
                value[nodes[k].name] = nodeToObject(nodes[k]);
            }
        }
        elements[IXBRL_ELEMENTS[i]] = value;
    }
    return elements;
}

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006
I've got a React project
code:
theme.js
src/
    components/
        Image.js
        OtherComponent.js
    views/
        BarView.js
Each image passed to Image.js has a body similar to:
code:
{
    src: 'foo.jpg",
    color: '#ABABAB",
}
Each time a new image is passed to the Image component, I want its color value to be included in the theme which OtherComponent and BarView could import from. Would there be a best practice for achieving something like this?

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