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
necrotic
Aug 2, 2005
I owe my brother big time for this!
I think React escapes strings automatically. Try it without the HTML escape lib.

Adbot
ADBOT LOVES YOU

Video Nasty
Jun 17, 2003

Knifegrab posted:

Yeah sorry guys, I was in fact using react and I used the componentWillRecieveProps hook to update the state on re-instancing.

Now I've got a UI question!

I have a comment system where users can leave comments on different pages. I store the plain text (sanitized) into a database, and when I display it I retrieve it from a database. I run the text to be returned through escape-html npm module to ensure that people cannot html/script inject my pages. However then when I display the text within my content it appears as this:

code:
Weaver's a tree. Once he has a "young weaver" attached to himself, he can't jump
Obviously for display purposes this is super ugly. I need to prevent quotes/apostrophes/square brackets etc from ebing interpolated as html but I also want them display nicely and not as the weird item they are being displayed as. Any ideas?


I want to say .decodeURIComponent() should resolve those to look normal?
I was mistakent.

Video Nasty fucked around with this message at 06:42 on Mar 18, 2017

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.
Ahh so it would seem react does! I again am a proven bonehead, thanks a ton guys!

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
I think I wrote some JS that is garbage, but I'm not experienced enough to know.

I have an array of objects, each object has an id property and a name property.

I have another array that is just full of numbers. I'm trying to create a new array out of this one, replacing the id with the name property in the other array.

Here's what I have.

data.genres.genres array
code:
[
  {
    id: 28,
    genre: 'Action'
  },
  ...and on and on
]
ids array
code:
[28, 44, 30, ...etc]
I wrote this function that iterates over each entry in the ids array. It works, I get back an array with the correct genre names pushed into it.
code:
const parseGenre = (ids) => {
    // Initialize an array to store matched IDS
    let genreList = [];

    // Iterate over each id in the passed in ids array
    ids.forEach((id) => {
      // For each id we iterate over, use that value to iterate over the
      // array containg the name value pairs for genre names
      data.genres.genres.forEach((genre) => {
        // If an entry in the genres array has an id that matches the id
        // that we're iterating over, push the name property in the genreList
        // array
        if (genre.id === id) {
          genreList.push(genre.name);
        }
      })
    });

    return genreList;
  }
Is this a terrible way to go about this?

Ranzear
Jul 25, 2013

Kinda terrible, but not because of the code. It's your data structures. You just need to utilize the indexes on your arrays instead of each entry floating in a relatively anonymous property (really, they have their own arbitrary indices depending on how inserted them).

You can just make your array index be the id instead, and each value can be an object or just the string of the genre name, to get a direct reference.

More conceptually: Arrays are just normal objects with extra methods tacked on. Array indices are just numeric object properties. You should use them like properties 90% of the time except when you have a particular case to push/pop/splice.

Just set it directly, like genres[28] = "action", or in a JSONy way:

code:
genres = {
	0:"butt stuff",
	4:"tentacles",
	28:"action"
}
Alternatively, if you still want to use the .genre and .id (even if redundant) properties, or want other properties to show up in the final list of objects:

code:
genres = {
	0:{
		id:0,
		genre:"butt stuff"
	},
	4:{
		id:4,
		genre:"tentacles"
	},
	28:{
		id:28,
		genre:"action"
	}
}
You're just making sure the index and id match so you always have a direct reference. Note also that Javascript doesn't care about sparse arrays, benefit of just being numeric properties.

With this, genre[28] is "action", so your code would be simplified to:

code:
let genrelist = [];
ids.forEach((id) => {
	genrelist.push(genres[id]);
	// or genrelist.push(genres[id].genre); in the second setup for just the name instead of the object
}

Ranzear fucked around with this message at 14:17 on Mar 19, 2017

ufarn
May 30, 2009

Xom posted:

That's just a static page, and I made the images low-res, so yes. Did you try running the demo? I should probably bold that link.

Edit: Should I put full-res images instead?
CSS-based image-resizing is extremely awful and inefficient, so you have to resize the images to the resolution they're going to end up being displayed in in advance. Having browsers do it for you is going to lead to ugly results.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Knifegrab posted:

code:
Weaver's a tree. Once he has a "young weaver" attached to himself, he can't jump
Obviously for display purposes this is super ugly. I need to prevent quotes/apostrophes/square brackets etc from ebing interpolated as html but I also want them display nicely and not as the weird item they are being displayed as. Any ideas?

You're double-escaping your text somewhere.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I

Ranzear posted:

Kinda terrible, but not because of the code. It's your data structures. You just need to utilize the indexes on your arrays instead of each entry floating in a relatively anonymous property (really, they have their own arbitrary indices depending on how inserted them).

You can just make your array index be the id instead, and each value can be an object or just the string of the genre name, to get a direct reference.

More conceptually: Arrays are just normal objects with extra methods tacked on. Array indices are just numeric object properties. You should use them like properties 90% of the time except when you have a particular case to push/pop/splice.

Just set it directly, like genres[28] = "action", or in a JSONy way:

code:
genres = {
	0:"butt stuff",
	4:"tentacles",
	28:"action"
}
Alternatively, if you still want to use the .genre and .id (even if redundant) properties, or want other properties to show up in the final list of objects:

code:
genres = {
	0:{
		id:0,
		genre:"butt stuff"
	},
	4:{
		id:4,
		genre:"tentacles"
	},
	28:{
		id:28,
		genre:"action"
	}
}
You're just making sure the index and id match so you always have a direct reference. Note also that Javascript doesn't care about sparse arrays, benefit of just being numeric properties.

With this, genre[28] is "action", so your code would be simplified to:

code:
let genrelist = [];
ids.forEach((id) => {
	genrelist.push(genres[id]);
	// or genrelist.push(genres[id].genre); in the second setup for just the name instead of the object
}

Ah, nice that seems way easier.

I agree on the data structure being dumb. The genre array and movie arrays are coming from an outside API. I wanted to try doing a little back end stuff and already had an express server set up for server-side rendering .ejs templates, so I thought I'd write a small API that the client talks to to get movie data, and have the server construct the data in something easier for the client to consume.

I'm definitely going to have the server convert that genre array into an object before it gets passed into the function that constructs the data to pass back to the client so I'm not looping over it unnecessarily for each movie.

Edit:

Jesus, that made the code that builds the movie list for the client so much cleaner.

code:
function movieList(moviesAndGenres) {
  return moviesAndGenres.movies.map((movie) => {
    return {
      title: movie.title,
      genre: movie.genre_ids.map((id) => { return moviesAndGenres.genres[id] })
    }
  });
}
Thanks for the help!

ddiddles fucked around with this message at 22:16 on Mar 19, 2017

Roadie
Jun 30, 2013

ddiddles posted:

Jesus, that made the code that builds the movie list for the client so much cleaner.

code:
function movieList(moviesAndGenres) {
  return moviesAndGenres.movies.map((movie) => {
    return {
      title: movie.title,
      genre: movie.genre_ids.map((id) => { return moviesAndGenres.genres[id] })
    }
  });
}

You can also trim this down a little more:

code:
function movieList (moviesAndGenres) {
  return moviesAndGenres.movies.map(movie => ({
    title: movie.title,
    genre: movie.genre_ids.map(id => moviesAndGenres.genres[id])
  }))
}
or potentially

code:
const movieList = (moviesAndGenres) => moviesAndGenres.movies.map(movie => ({
    title: movie.title,
    genre: movie.genre_ids.map(id => moviesAndGenres.genres[id])
}))
Implicit returns are neat.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
Oh, I thought .map() required a return statement in the callback?

Edit: On further reading, I was mixing that up with wanting to return something from the forEach callback. Nice, refactor upon refactor upon refactor.

ddiddles fucked around with this message at 23:00 on Mar 19, 2017

Roadie
Jun 30, 2013

ddiddles posted:

Oh, I thought .map() required a return statement in the callback?

Edit: On further reading, I was mixing that up with wanting to return something from the forEach callback. Nice, refactor upon refactor upon refactor.

If you have an arrow function without a block, the single statement in it is automatically returned. The ({}) syntax serves as a disambiguation for object literal vs function block.

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.
And just to clairfy what Roadie said because I myself am an example man:

code:
const things = items.map((item) => {
   return item.thing;
});
is equivalent to:

code:
const things = items.map((item) => item.thing);

Roadie
Jun 30, 2013

Knifegrab posted:

And just to clairfy what Roadie said because I myself am an example man:

code:
const things = items.map((item) => {
   return item.thing;
});
is equivalent to:

code:
const things = items.map((item) => item.thing);

If it's only a single parameter, you don't even need the parentheses around it.


code:
const things = items.map(item => item.thing)
code:
const things = items.map(item => ({a: item.a, b: item.b}))

Roadie fucked around with this message at 05:59 on Mar 20, 2017

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.

Roadie posted:

If it's only a single parameter, you don't even need the parentheses around it.


code:
const things = items.map(item => item.thing)
code:
const things = items.map(item => ({a: item.a, b: item.b}))

True but as a rule of purpose I always use wrap my arrow function parameters. I think its a good practice to follow IMO. Obviously this is highly debatable.

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

Knifegrab posted:

True but as a rule of purpose I always use wrap my arrow function parameters. I think its a good practice to follow IMO. Obviously this is highly debatable.

The unwrapped version is interesting because it implicitly returns the expression, so not only do you save on () {}, but the return statement as well. Works best for trivial things, if complex would probably be best to break it down further, though in that case would probably make more sense to move it to a dedicated function instead of anonymous.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
I love es6.

Thanks for the explanation dudes!

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.

Skandranon posted:

The unwrapped version is interesting because it implicitly returns the expression, so not only do you save on () {}, but the return statement as well. Works best for trivial things, if complex would probably be best to break it down further, though in that case would probably make more sense to move it to a dedicated function instead of anonymous.

Only unwrapping the {} implies the return. Whether or not the paramters are wrapped don't affect the implied return. Unwrapping the parameters only works when there is a single parameter as well, so its such an edge case I always wrap my parameters. I think it reads better.

Dominoes
Sep 20, 2007

Hey dudes. How can I make React work? The tutorials I'm seeing focus on JSX syntax, then link to node packages. This is a front-end-framework that shouldn't have anything to do with node AFAIK, so I'm missing something. How do I run a JSX file on a web page, without worrying about server-frameworks and package managers?

The Fool
Oct 16, 2003


Dominoes posted:

Hey dudes. How can I make React work? The tutorials I'm seeing focus on JSX syntax, then link to node packages. This is a front-end-framework that shouldn't have anything to do with node AFAIK, so I'm missing something. How do I run a JSX file on a web page, without worrying about server-frameworks and package managers?

People working with React commonly use npm for package management and node+express as a local dev server. They are by no means required and you can run react using <script> tags if you really wanted to.

I'd recommend just using create-react-app and not worrying too much about what's going on behind the scenes if you're just starting out.

Create-react-app: https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html

Thermopyle
Jul 1, 2003

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

Dominoes posted:

Hey dudes. How can I make React work? The tutorials I'm seeing focus on JSX syntax, then link to node packages. This is a front-end-framework that shouldn't have anything to do with node AFAIK, so I'm missing something. How do I run a JSX file on a web page, without worrying about server-frameworks and package managers?

At a high level:

People using React use a thing called webpack. Webpack takes node modules and bundles them up into a javascript file that you then include in your page via a script tag. This is nice because you can install all sorts of libraries and use them in your frontend work kind of like you didn't have to work in the terrible environment that is the browser.

So, I know you do python so it kind of works like this:

npm install react is the equivalent of pip install requests.
package.json is kind of the equivalent of requirements.txt

When you're developing you can use a thing called webpack-dev-server that automatically rebundles your code and all of the dependencies when you save a file and then refreshes your browser pages showing your app. When you're ready to put your code into production you call the appropriate commands to tell webpack to spit out a bundle.js file that contains all your code as well as all the libraries you've installed with npm install.

create-react-app streamlines a lot of the process here...particularly for beginners, so I'd recommend you use that and ask questions as you work with it.

Dominoes
Sep 20, 2007

Thanks dudes. Ironically, it was installing create-react-app, and seeing webpack in search results that made me even more confused. Looks like this is no ordinary JS library!

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
It's possible to use react without using NPM or webpack for bundling, but just thinking about it makes me anxious.

People use Webpack and Babel because it allows you to write this:

code:
const myRadComponent = (props) => {
  return (
    //JSX stuff
    <div>
      <h2>Oh man this is so fun</h2>
    </div>
    );
}
And it gets transpiled by Babel and bundled up into a JS file you include in your page with Webpack. Otherwise you'd have to write it in standard JS, which would look like.

code:
var myRadComponent = function myRadComponent(props) {
  return React.createElement(
    "div",
    null,
    React.createElement(
      "h2",
      null,
      "Oh man this is so fun"
    )
  );
};
And thats just code for displaying an H2. I don't even want to imagine what the code would look like including the logic to actually render it to the page.

Edit: Guess its not bad.

code:
ReactDOM.render(React.createElement('myRadComponent', null), document.getElementById('app'));

ddiddles fucked around with this message at 23:43 on Mar 20, 2017

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Can someone give me the cliff notes on what the curly braces do in this ES6 import statement?
code:
import { ImportedThing } from './sourceFile'
I just spent a lot of time hunting down a bug where the problem was missing curly braces. No compile-time errors, and the run-time error had me pouring through my render methods for syntax errors (although I thought that they should have been caught in the traspilation).

I'm new with ES6 / transpilers / webpack / etc. Coming slowly, but there are so many magic wands.

Here's the error message that I got:

quote:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `ParentComponent`

Kekekela
Oct 28, 2004
Curly braces mean you're importing a non-default member.


export default butts
import butts

export butts
export dongs
import {butts, dongs}

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Kekekela posted:

Curly braces mean you're importing a non-default member.

Member of... the file? This is a toy / tutorial project, and sourceFile.js consists only of some import lines and a single
code:
export const ReactComponent = () => ( <div> I get rendered! </div> )
declaration.

edit:

Your edit provides a bit more context to chew on. Will play with some keywords. Wish me butts.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
exporting essentially generates the following object

code:
// buttsfile.js
export default butts
export function dongs() {}

// actually exports the following object in node
{
  'default': butts,
  'dongs': dongs
}
Importing is a destructuring of the object where:

code:
// otherfile.js
import TheThing, {dongs} from './buttsfile.js'

// actually does this
var TheThing = require('./buttsfile.js).default
var dongs = require('./buttsfile.js).dongs
That's why the default import can be named whatever you like, and also why the default import will return as undefined if you didn't 'export default' in the exporting file.

Dominoes
Sep 20, 2007

ddiddles posted:

It's possible to use react without using NPM or webpack for bundling, but just thinking about it makes me anxious.

People use Webpack and Babel because it allows you to write this:

And thats just code for displaying an H2. I don't even want to imagine what the code would look like including the logic to actually render it to the page.

Edit: Guess its not bad.

code:
ReactDOM.render(React.createElement('myRadComponent', null), document.getElementById('app'));
Thanks!

What's the best way to make TypeScript not throw the error 'property value does not exist on type Element' for code like this?:
JavaScript code:
myRow.querySelector('.myClass').value = nextNum
Casting as <HTMLInputElement> Causes the code to break entirely, although it does allow error-free use of querySelector in other cases.

Dominoes fucked around with this message at 20:26 on Mar 23, 2017

LP0 ON FIRE
Jan 25, 2006

beep boop
I've been fed up with Polymer's dropdown functionality, so I decided to edit a w3schools example. Seems to work fine on PC browsers, but I can't seem to implement a way to have it work on iOS to capture touches outside the button and menu to close it. If I use a touchend event listener the same way I use click, it closes the menu immediately after I try touching an option on the list.

CSS:
code:
<style>

/* The container <div> - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}



/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu*/
.show {display:block;}

</style>

HTML:
code:

<div class="dropdown">

  <button 
onclick="showUserDropDown()" 
class="userOptionsMenuButton" 
style='padding-right:0px; padding-bottom:0px; font-size:12px; position:relative; top:$userTopPixelPos;'>
<iron-icon icon='icons:arrow-drop-down'></iron-icon>&nbsp;$user_check</button>

  <div id="myDropdown" class="dropdown-content">
    <a class="userOptionsMenuItemLink" href='$profileHREF'>Profile</a>
    <a class="userOptionsMenuItemLink" href='logout.php'>Sign out</a>
  </div>

</div>


java script:
code:
window.addEventListener('click',handler,false);

window.addEventListener('touchend',handler,false);

// Close the dropdown menu if the user clicks outside of it
function handler(event){
  if (!event.target.matches('.userOptionsMenuButton') && 
      !event.target.matches('.dropdown-content')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Another ES6 / React question.

I'm following this Lynda.com React.js Essential Training course, which I'm generally finding informative and good, but I'm often thrown for a loop at some of the author's js conventions. I'm new to ES6 and bad at js in general, but I'm really stuck for rationale at some of the code she writes.

The current example is a function for adding an item to a component's array of data:

JavaScript code:
// author's code
addDay(newDay){
    this.setState({
        allSkiDays: [
            ...this.state.allSkiDays,
            newDay
        ]
    })
}

// why not this?
addDay(newDay){
	this.state.allSkiDays.push(newDay)
}
It feels like a lot of modern language features are being shoehorned in for their own sake, but I don't feel very qualified to be making these judgements.

ROFLburger
Jan 12, 2006

Newf posted:

It feels like a lot of modern language features are being shoehorned in for their own sake, but I don't feel very qualified to be making these judgements.

State changes should only ever be made through the setState method so that React can trigger updates and lifecycle methods.

If the '...' business is confusing, it's called the Spread Operator, you can think of it as unzipping the members of this.state.allSkiDays and placing them in to the new allSkiDays array, along with another item, newDay

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

If it helps, that could also be written without it like this:
code:
addDay(newDay){
    this.setState({
        allSkiDays: this.state.allSkiDays.concat(newDay)
    })
}

ROFLburger fucked around with this message at 23:08 on Mar 24, 2017

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Newf posted:

Another ES6 / React question.

I'm following this Lynda.com React.js Essential Training course, which I'm generally finding informative and good, but I'm often thrown for a loop at some of the author's js conventions. I'm new to ES6 and bad at js in general, but I'm really stuck for rationale at some of the code she writes.

The current example is a function for adding an item to a component's array of data:

JavaScript code:

// author's code
addDay(newDay){
    this.setState({
        allSkiDays: [
            ...this.state.allSkiDays,
            newDay
        ]
    })
}

// why not this?
addDay(newDay){
	this.state.allSkiDays.push(newDay)
}

It feels like a lot of modern language features are being shoehorned in for their own sake, but I don't feel very qualified to be making these judgements.

E: I'm an idiot, so rarely do I use the return of push that I forgot it was the length not the array.

It does, however a thing to keep in mind is push on its own will mutate the old state and return not the array but the length, an identical result would come from allDays.concat([newDay])

Maluco Marinero fucked around with this message at 23:22 on Mar 24, 2017

Kekekela
Oct 28, 2004

Newf posted:

Another ES6 / React question.

I'm following this Lynda.com React.js Essential Training course, which I'm generally finding informative and good, but I'm often thrown for a loop at some of the author's js conventions. I'm new to ES6 and bad at js in general, but I'm really stuck for rationale at some of the code she writes.

The current example is a function for adding an item to a component's array of data:

JavaScript code:
// author's code
addDay(newDay){
    this.setState({
        allSkiDays: [
            ...this.state.allSkiDays,
            newDay
        ]
    })
}

// why not this?
addDay(newDay){
	this.state.allSkiDays.push(newDay)
}
It feels like a lot of modern language features are being shoehorned in for their own sake, but I don't feel very qualified to be making these judgements.

spread gives you immutability which can be an important consideration. Its what you'll find being used in reducers in redux for example (this is actually where I started using them because it was necessary which lead to me using them all over the place because it was convenient)

Roadie
Jun 30, 2013

ROFLburger posted:

State changes should only ever be made through the setState method so that React can trigger updates and lifecycle methods.

This is the key thing. Other current frameworks do the details differently, but there's always some level of mushy workaround to be able to reliably detect that you changed X and have that trigger all your things that are watching for new values of X.

This isn't necessary for all uses, but it's generally just a lot easier to structure everything that way and then you can throw in "send a thing to the server when this value changes" or "handle JS-based resizes of components incorporating window size" without having to rebuild everything to accommodate it.

Roadie fucked around with this message at 21:48 on Mar 27, 2017

LP0 ON FIRE
Jan 25, 2006

beep boop
ES6 is awesome, but I'm also weary of using it since the compatibility is so recent for iOS. I can use babeljs.io to convert it over into something equivalent, but I wish I could just keep writing ES6 and have it convert over behind the scenes. I'm using VS Code. Any good solutions for this?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

LP0 ON FIRE posted:

ES6 is awesome, but I'm also weary of using it since the compatibility is so recent for iOS. I can use babeljs.io to convert it over into something equivalent, but I wish I could just keep writing ES6 and have it convert over behind the scenes. I'm using VS Code. Any good solutions for this?

The toytorial work that I've been doing has a fancy setup with npm and Webpack, in conjunction with babel which watches the directory and recompiles whenever there are file changes, and serving the compiled project.

JavaScript code:
// package.json
{
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-loader": "^6.2.7",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "webpack": "1.13.3",
    "webpack-dev-server": "^1.16.2"
  }
}
//webpack.config.js
module.exports = {
    entry: "./src/index.js",
    output: {
        path: "dist/assets",
        filename: "bundle.min.js",
        publicPath: "/assets/"
    },
    devServer: {
        inline: true,
        contentBase: './dist',
        port: 3000
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules)/,
                loader: ['babel'],
                query: {
                    presets: ['es2015', 'react', 'stage-0']
                }
            }
        ]
    }
}
That said, I'm still lost as to how to debug this ES6 code, since all of it ends up bundled. Also note that this setup is using the webpack 1, which is now out of date.

Kekekela
Oct 28, 2004

Newf posted:

That said, I'm still lost as to how to debug this ES6 code, since all of it ends up bundled

If you're in chrome dev tools in the sources tab go down to the bottom of the treeview and select your source files from the webpack node. Might need to enable sourcemaps in your webpack config for that to work. And webpack-dev-server is doing the hot reloading, not babel.

Dominoes
Sep 20, 2007

LP0 ON FIRE posted:

ES6 is awesome, but I'm also weary of using it since the compatibility is so recent for iOS. I can use babeljs.io to convert it over into something equivalent, but I wish I could just keep writing ES6 and have it convert over behind the scenes. I'm using VS Code. Any good solutions for this?
I'm a JS noob, by PyCharm does it automatically for TypeScript; needed to make a tsconfig.json, and enable compiler in the settings. I suspect it (and WebStorm) will do the same for ES6. And like Kek said, Chrome's web tools will link the errors to your pre-compile file. Firefox doesn't, at least by default.

Related: Why does TypeScript support only a subset of ES6 compiling to old JS? Are there any compilers that do Typescript and full-ES6?

Dominoes fucked around with this message at 02:57 on Mar 28, 2017

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Dominoes posted:

I'm a JS noob, by PyCharm does it automatically for TypeScript; needed to make a tsconfig.json, and enable compiler in the settings. And like Kek said, Chrome's web tools will link the errors to your pre-compile file. Firefox doesn't, at least by default.

Related: Why does TypeScript support only a subset of ES6 compiling to old JS? Are there any compilers that do Typescript and full-ES6?

Typescript is less aggressive in supporting features that are not actually 100% confirmed to be implemented yet. Babel contains all sorts of transpiles that may not actually ever make it into native support.

Babel can sort of get away with that because of its configurable nature and no actual promise of backwards compatibility, however that does mean 20 projects using Babel may in fact be using 20 slightly different variants of the JavaScript of the future, depending on how they've been configured.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I

Newf posted:

The toytorial work that I've been doing has a fancy setup with npm and Webpack, in conjunction with babel which watches the directory and recompiles whenever there are file changes, and serving the compiled project.

JavaScript code:
// package.json
{
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-loader": "^6.2.7",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "webpack": "1.13.3",
    "webpack-dev-server": "^1.16.2"
  }
}
//webpack.config.js
module.exports = {
    entry: "./src/index.js",
    output: {
        path: "dist/assets",
        filename: "bundle.min.js",
        publicPath: "/assets/"
    },
    devServer: {
        inline: true,
        contentBase: './dist',
        port: 3000
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules)/,
                loader: ['babel'],
                query: {
                    presets: ['es2015', 'react', 'stage-0']
                }
            }
        ]
    }
}
That said, I'm still lost as to how to debug this ES6 code, since all of it ends up bundled. Also note that this setup is using the webpack 1, which is now out of date.

Add "devtool: inline-source-map" to your webpack config

Adbot
ADBOT LOVES YOU

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen

LP0 ON FIRE posted:

ES6 is awesome, but I'm also weary of using it since the compatibility is so recent for iOS. I can use babeljs.io to convert it over into something equivalent, but I wish I could just keep writing ES6 and have it convert over behind the scenes. I'm using VS Code. Any good solutions for this?

Have you checked out jspm?

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