Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

General JavaScript

Featured Replies

  • Replies 422
  • Views 70.5k
  • Created
  • Last Reply

Top Posters In This Topic

Most Popular Posts

  • As soon as I saw the JS videos with that Mattias guy, I knew who he was straight away. He posts some really useful answers on Quora. I'd advise signing up if you haven't already. I've wasted hours re

  • Console.table, ladies and gentleman http://jsfiddle.net/juu5fx82/.   You need to use the JS console obviously, and hit 'run'. I never knew this existed.

  • jQuery's modular, you can build a custom version via Grunt, its pretty simple.   Before v3.0, which now uses requestAnimationFrame and Promises/A+, I'd use a build without Effects and Ajax with Velo

  • Author

Does anyone know how to get a .jsx extension working with webpack and babel? I keep switching between projects, and it drives me nuts having to manually change my syntax highlighting each time.

I've tried the below and it still doesn't compile.

{ test: /\.(js|jsx)$/, use: 'babel-loader' }

 

Does anyone know how to get a .jsx extension working with webpack and babel? I keep switching between projects, and it drives me nuts having to manually change my syntax highlighting each time.

 

I've tried the below and it still doesn't compile.

{ test: /\.(js|jsx)$/, use: 'babel-loader' }

The regex below should cover .js and .jsx although your regex above should also match. I can't see why the config above is not compiling though Babel. Do you have your babelrc configured correctly with the presets you require?

/\.jsx?$/
  • Author

The regex below should cover .js and .jsx although your regex above should also match. I can't see why the config above is not compiling though Babel. Do you have your babelrc configured correctly with the presets you require?

/\.jsx?$/

 

As well as the regex above, I had to add the following to my webpack config to get it to work:

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

It looks like the alternative is to explicitly add the file extension to any require or import statement, otherwise webpack has no idea what to do.

That makes sense, I think with Webpack questions we should post our entire config as there are many moving parts that can break things that might be seemingly unrelated :)

 

With the extensions as I am sure you know now that you can add anything like .scss, .jpg etc then we don't need to specify them in our imports. It ties you into Webpack but I don't think that's a bad thing considering how well established and maintained Webpack is now.

Edited by rbrtsmith

resolve: {
    modules: ['src', 'node_modules'],
    extensions: ['.js', '.jsx', '.scss'],
  },

One neat thing with the resolve config that you can pass is `modules`. This will allow you to import directly from a path within your modules.

 

So say you were in my-project/src/components/header/title.jsx...

 

// to import a utility we could do
import myUtility from '../../utils/myUtility


// OR
import myUtility from 'utils/myUtility'

It's pretty handy, especially as a project grows and a component might have to be moved elsewhere - it means you then wont have to go updating all the paths for relative imports.

  • 3 weeks later...
  • 2 weeks later...

Blimey...

It's quite extensive. The Author has approved my PR to get Nebula added to the UI Toolset list... Just gotta get him to merge now !

Edited by rbrtsmith

  • 2 weeks later...
  • 2 weeks later...
  • Author

Does anyone know how Babel Polyfill works? If I add it to my file, does it just run through, check the code to see if any new features are being used, and polyfill them, or does it just include a massive file that polyfills everything regardless?

Edited by Jack

It polyfills various browser APIs that might not be available in your target browser, so it will polyfill things like fetch() and Object.assign() for example.

Make sure you add it at the top of your main entry point so that it runs before anything else. IIRC it will bundle in all the polyfills.

I'd recommend checking out https://github.com/babel/babel-preset-env to keep the bundle size as small as possible for your target browsers.

Edited by rbrtsmith

  • Author

It polyfills various browser APIs that might not be available in your target browser, so it will polyfill things like fetch() and Object.assign() for example.

 

Make sure you add it at the top of your main entry point so that it runs before anything else. IIRC it will bundle in all the polyfills.

 

I'd recommend checking out https://github.com/babel/babel-preset-env to keep the bundle size as small as possible for your target browsers.

 

So if you don't use Object.assign, for example, it's still include it in the bundle? This isn't ideal really, I'll probably just polyfill for each new method I need and import them.

 

So if you don't use Object.assign, for example, it's still include it in the bundle? This isn't ideal really, I'll probably just polyfill for each new method I need and import them.

 

Pretty sure that is what Babel Polyfill does. preset-env should polyfill just what you need for the specified environments. Maybe Tree-shaking removes unused polyfills although again I'm not 100% sure, it's been a while since I last did client-side bundling!

Edited by rbrtsmith

I assume that tree shaking with Webpack 2.0 would handle unused polyfills since they are individually exported modules?

  • Author

I assume that tree shaking with Webpack 2.0 would handle unused polyfills since they are individually exported modules?

 

Yeah I'd imagine so.

 

I ended up using a polyfill off NPM instead because there's only one unsupported ES6 feature I need in the code. If this grows I'll switch it out.

I thought I'd share this https://github.com/rbrtsmith/nebula-css-react-starter

It's basically a starting point for React projects that consume Nebula-CSS.

Has a webpack setup ready for development and production builds.

uses webpack-dev server for development

 

Production build sets the correct node_env for react production, minifies all code and removes any source-maps

 

Pretty minimal at this stage so only handles ES6 and Sass/CSS imports CSS currently bundles with the JavaScript, you'd need a webpack ExtractText plugin to bundle the CSS as a seperate file. Would also require some additional work for server-side rendering but at this stage I wanted to keep things as simple as possible.

  • Author

 

Gotta keep those devs employed!

 

Since I've been at the BBC, we've rebuilt football scores in PHP, AngularJS and now React.

 

Did you do any Angular work? I've never liked that framework, V2 is far too big, and requires knowledge of Typescript and RXJS to take full advantage of it.

Angular is just monolithic I'd hate to have to be working with that framework now. One of the teams at Sainsbury's in Manchester started using GraphQL and Relay - actually they're actively contributing to Relay and apparently it's ground-breakingly good. It's pretty high on my learn-stuff-todo list.

  • Author

Angular is just monolithic I'd hate to have to be working with that framework now. One of the teams at Sainsbury's in Manchester started using GraphQL and Relay - actually they're actively contributing to Relay and apparently it's ground-breakingly good. It's pretty high on my learn-stuff-todo list.

 

Yeah GraphQL looks really good, I love the idea of it. I don't know much about Relay, other than a new rewrite is out soon, so it might be worth holding off for now.

  • Author

 

Yeah, the original live pages (pages that have /live/ in the url) were based on Angular 1. When I first started I was doing PHP, but I soon moved over to the team working on live components, so had to learn Angular 1. I quite liked it at the time actually, but that's because I was coming from a vanilla JS/jQuery background. Compared to using vanilla JS or jQuery, Angular is a big improvement. It's much more testable and some of the ideas in it were pretty good at the time.

 

As Rob said above though, they tried to do everything inside it, and two way databinding was also quite expensive. There's also this Angular DSL that you have to learn, whereas React is just Javascript at the end of the day. I find React much nicer to work with, especially when you start doing nice stuff with compound components and things like that.

 

I remember talking to you about GraphQL when we met in Manchester. I'm currently writing my own app and I'm planning to take a look at GraphQL at a later stage. Potentially I'll refactor my REST API for a GraphQL one at some point.

 

I tried writing some CSS the other day, for the first time in ages, and it was actually embarrassing. I'll get back into the swing of things soon I'm sure, but trying to do layout in CSS after barely writing a line of it in 3-4 years was... fun, let's say ;-)

 

One of the issues I have at the moment is that I'm kinda stuck in this weird BBC middle tier level that isn't quite proper front end (we have lots of reusable components, so I just don't have to write css really, and even then we have a specialised front end guy who does most of the css), and it's not backend either, because we have a separate team that handles the infrastructure. So one of the reasons I'm making this app is to force myself to touch every layer. I've seen myself as a backender for most of my career, but in the modern world we live in, backend generally means you're good with the cloud - when I was at EA it was all single servers with a database and apache/php. I'm doing this to push myself to learn all that stuff basically. Tbh it's been a bit of fun.

 

Just don't expect my CSS to be much good.

 

At the end of the day, CSS is just "float:left;" anyway. Let's face it ;-)

 

Yeah, things have got a bit crazy on both ends of the spectrum. With backend I've seen quite a few people starting to get into AWS Lambda and Serverless. GraphQL is really well suited to a Serverless architecture.

 

I've just started the Wes Bos tutorial on Node but got distracted by Express. I can't believe how powerful that module is, I ended up playing around with Express by itself for a while, which probably isn't a bad thing considering most Node apps use it. I'm planning on switching out Pug for a different templating engine soon, I just can't handle the syntax, and doing so should help reenforce how that part works too.

  • Author

Yeah, Bitbucket Pipelines looked good to me as soon as I saw the product demo. We use Bitbucket at work and I really like it. I'm not sure what your experience is setting up Node + Nginx, but there's a course on FEM with Jem Young where he walks through how to do it on Digital Ocean.

 

With the CSS stuff, I'd personally use CSS grid if it's not a customer facing app. I've wanted to learn it for a while but I don't have a good reason to use it at work. CSS in JS is interesting, but every week there's a new library that's "better" than the previous one, it just seems to be a bit unstable at the moment. I don't think I'd get that much benefit out of it either, ITCSS by Harry Roberts has been working fine for me.

I have done the Wes Bos course, there's some great things, but I don't see much value in the Pug templating side. I'd prefer the backend to just be an API that sends out the JSON data that talks to a React frontend - that can all be server rendered. I can't imagine it being that hard to change it up.

Yeah, Bitbucket Pipelines looked good to me as soon as I saw the product demo. We use Bitbucket at work and I really like it. I'm not sure what your experience is setting up Node + Nginx, but there's a course on FEM with Jem Young where he walks through how to do it on Digital Ocean.

 

With the CSS stuff, I'd personally use CSS grid if it's not a customer facing app. I've wanted to learn it for a while but I don't have a good reason to use it at work. CSS in JS is interesting, but every week there's a new library that's "better" than the previous one, it just seems to be a bit unstable at the moment. I don't think I'd get that much benefit out of it either, ITCSS by Harry Roberts has been working fine for me.

ITCSS has been working fine for me too. We build some pretty large scale apps at Sainsbury's and CSS was never a problem with ITCSS. So when the CSS-JS solutions all say they fix the issues that ITCSS already fixes I am reluctant to change. It would also mean me re-writing my entire Nebula framework and the benefit just isn't there for me. Yet.

  • Author

ITCSS has been working fine for me too. We build some pretty large scale apps at Sainsbury's and CSS was never a problem with ITCSS. So when the CSS-JS solutions all say they fix the issues that ITCSS already fixes I am reluctant to change. It would also mean me re-writing my entire Nebula framework and the benefit just isn't there for me. Yet.

 

I think it makes sense for companies that can't refactor their CSS to fit this architecture, or have a legacy codebase. Being able to split out components to using their own scoped styles will make things easier, especially when it comes to refactor at a later stage, the devs won't have to touch any components.

React 16 is in beta now (the one with fiber) one of the nice features is how it deals with component errors https://facebook.github.io/react/blog/2017/07/26/error-handling-in-react-16.html.

I also like that you can render an array of nodes now rather than having to add an extra <div> at the root.

  • Author

I also like that you can render an array of nodes now rather than having to add an extra <div> at the root.

 

That was the most requested feature since being open sourced apparently.

  • 2 weeks later...
  • Author

I'm having a bit of a nightmare with Mocha. All of my tests are passing, but the code references a variable on the global scope (Google Tag Manager), the problem is, every time I run my tests it moans about reference errors because Node doesn't have a window object, does anyone know how to get around this? It's not actually breaking anything but it clutters up the console.

 

Edit: Never mind I just wrapped a conditional around the GTM call and it's working on both now.

Edited by Jack

Look at using something like JsDom or mock out window references.

I went he mocking route.
Here I create some aliases to the window globals that I wish to mock

const addEListener = (e, cb) =>
  window.addEventListener(e, cb)

const removeEListener = (e, cb) =>
  window.removeEventListener(e, cb)

export {
  addEListener,
  removeEListener
}

I consume them in this component

import { Component, createElement as E } from 'react'
import T from 'prop-types'
import { classNames, addEListener, removeEListener } from '../../utils'

class NavbarDropdownToggle extends Component {
  constructor() {
    super()

    this.state = {
      isOpen: false
    }
  }

  componentDidMount() {
    addEListener('click', this.handleClickOutside)
  }

  componentWillUnmount() {
    removeEListener('click', this.handleClickOutside)
  }

  handleClick = () =>
    this.setState({
      isOpen: !this.state.isOpen
    })


  handleClickOutside = ({ target }) =>
    this.setState({
      isOpen: !this.button.contains(target)
        ? false
        : this.state.isOpen
    })

  render() {
    const { node, children, className, ...rest } = this.props
    return E(
      node || 'button',
      {
        onClick: this.handleClick,
        ref: (n) => { this.button = n },
        className: classNames(
          'c-navbar__dropdown-toggle', className,
          { 'is-open': this.state.isOpen }
        ),
        ...rest
      },
      children
    )
  }
}

NavbarDropdownToggle.propTypes = {
  className: T.string,
  node: T.string,
  children: T.node.isRequired
}

export default NavbarDropdownToggle

And tested here

import React from 'react'
import { shallow, mount } from 'enzyme'

import { Navbar } from '../'

import { addEListener, removeEListener } from '../../../utils/window'

jest.mock('../../../utils/window')

describe('<Navbar.Dropdown.Toggle />', () => {
  it('adds a click handler to the window when mounted and removes it when it unmounts', () => {
    const mockAddEventListener = jest.fn()
    const mockRemoveEventListener = jest.fn()
    addEListener.mockImplementation(mockAddEventListener)
    removeEListener.mockImplementation(mockRemoveEventListener)

    const $ = mount(<Navbar.Dropdown.Toggle>_</Navbar.Dropdown.Toggle>)
    const handleClickOutside = $.instance().handleClickOutside
    expect(mockAddEventListener).toHaveBeenCalledWith('click', handleClickOutside)
    $.unmount()
    expect(mockRemoveEventListener).toHaveBeenCalledWith('click', handleClickOutside)
  })
})


This is in Jest so the syntax will be different. For Mocha you will need to bring in Sinon to mock. These are reasons I use Jest because all this stuff just comes out of the box.

AFAIK Enzyme's simulate method only works on React nodes and not on real DOM nodes, as I am testing here for click events on the actual document itself itself. The expected behaviour is that if you click anywhere on the document that is not this component or a descendant of it, the state is updated to set isOpen to false.
I am not sure how else to test the behaviour.

Whilst mocking might not be the best solution it does enable me to test that the component behaves as expected. I'd be happy to see a better way of doing this :)

Edited by rbrtsmith

  • Author

I've not done much of this kinda stuff using Jest yet (started using Jest for some pure JS stuff, but not had to build anything new in React since using it, so not quite as familiar with JSDOM). However, I've never had to mock out the window object like this before and it doesn't sound like a great idea to me.

 

I've tended to use Karma and Mocha/Jasmine in the past, and that gives you a real DOM to work with if you're combining it with something like PhantomJS.

 

I'd be surprised if you have to mock out the window object in this way. I'd prefer to use a real DOM, or a DOM like representation that's so close to reality it might as well be the real thing.

 

If you're using Karma with Phantom then you have a real window object because you have a real DOM, and the problem goes away.

 

Good point, I could probably use Chrome's new headless browser for this. Do you find any performance decreases testing with a headless browser rather than just Node?

  • 3 weeks later...
  • 3 weeks later...
  • Author

Just filled out the FEM 2018 course picker, they've had some incredible courses on this year. Also, it's the last day of the sale, you can save $178, and if you're lucky, Marc will save that price in your account permanently.

  • 2 weeks later...
Guest
This topic is now closed to further replies.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.