Introduction to the JavaScript Array reduce() method

Array.prototype

JavaScript LogoJavaScript’s Array reduce() method can be a bit confusing. It doesn’t “reduce” any of the array elements, in fact they are not changed. This method “reduces” the array to one value.

An array is essentially a list, and in JavaScript, that list can contain any valid value. Most array-specific tasks involve “doing something” with the array, or you may need to “do something” with every array element. But what if you need to convert the array into one value? In other words, if the array contains a list of values, what one value could represent all of those values? In this article, I’ll explain how the JavaScript Array reduce() method provides a way to solve this problem.

An important concept to think about is how you can translate a list of values into one, that represents all of them. In some languages, all arrays must be “typed”. In other words, every array element must be of the same type. In JavaScript, you’re not limited in this way; a JavaScript array can contain any number of numbers, strings, arrays or any other valid JS value type.

It’s true that Typescript can limit this kind of freedom, but you’re not required to use Typescript and ultimately, Typescript compiles down to JavaScript. So, the reality of dynamic arrays in JavaScript has not changed. Therefore, if you want to reduce all of the values in your array to one, it’s important to consider the type of each element. If all of the elements in your array are of the same type, things are fairly simple. If the types vary, however, that can get complicated. Of course, that discussion is beyond the scope of this article, but I just wanted to point it out.

Using a while-loop – Example # 1

See the Pen Array.prototype.reduce() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

A “while” loop is a valid way to iterate a JavaScript array and that approach has worked for us here. We effectively “reduced” all of the elements of our array to the one value of 79, and we did this by adding each array element to the “getTotal” variable.

When I said that this approach “…has worked for us”, you may notice that I didn’t say that it “…worked well”. This is because the approach we took solved a problem, but created a couple of issues, the main one being boilerplate code. Most of the code in our “while” loop will be repeated if / when we need to solve the same problem elsewhere in our code. In addition to that, we have created an “i” variable to keep track of our counting during our “while” loop. It may seem innocent, but the more variables we create, the more variables we need to manage. Fewer variables is better.

Using the JavaScript Array reduce() method – Example # 2

See the Pen Array.prototype.reduce() – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The Array reduce() method has dramatically simplified things in Example # 2. Notice how, in the getTotal the variable is now an anonymous function. In this function, we add the accumulator and currentValue arguments. Now you may be wondering: “What are the accumulator and currentValue arguments?” Well, take a look at the last line of code: milesPerDay.reduce(getTotal). What’s happening here is, we’re executing the .reduce() method of our “milesPerDay“, passing it the getTotal as an argument. This is the anonymous function that we detailed a few sentences ago.

So, the reduce method iterates the array and provides access to not only the currently iterated value (i.e. the current array element), but also the value that was returned by the previous execution of this function. This allows you to “accumulate” values across the array.

The arguments passed to the JavaScript Array reduce() method –
Example # 3

See the Pen Array.prototype.reduce() – Solution – 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 3 does not provide any additional value with respect to solving the problem; the solution from Example # 2 is solid. The purpose of Example # 3 is to offer more detail about the arguments that are passed to the function provided to the Array reduce() method.

As demonstrated in the UI, the first argument is the accumulated value that’s being created as you iterate the array (i.e. the value returned by the last execution of this same function). The second argument, “currentValue”, is the value of the current array element. In the third, the index of the current array element is provided, and in the last, we see the array over which you are iterating.

I decided to show the value of the “array” argument to demonstrate that the Array reduce() method does not itself make any changes to the original. You can do that within the function passed to the Array reduce() method, but reduce() itself does not make any such changes. What you choose to do with these arguments is up to you, but just know that they’re helpful in building the logic you need to reduce your array to one final value.

Introduction to the JavaScript Array map() method

Array.prototype

JavaScript LogoJavaScript’s array map() method allows you to “do something” with each element of an array. This has always been possible, but the map() method’s syntax is simple and elegant.

When you have an array, you’ll eventually want to “do something” with it. You may, for example, want to do something with the entire array, such as showing all of its elements in the UI. But what about when you want to “do something” with each element in that array? This poses a bit more of a challenge.

First, you’ll need to iterate the array, which requires some kind of loop. Second, you’ll need to keep track of your iteration process, which requires a counter variable (which requires you to control that variable’s scope). This may seem like no big deal, but it’s work and each time you want to solve the same problem, you’re writing code that’s virtually identical, but not entirely the same, so you start to copy and paste.

This kind of repetitive boilerplate code is tedious, it must be managed, and as repeated code, it becomes a red flag. So, since this kind of coding presents unnecessary problems, what we’ll cover in this article, is how the JavaScript Array map() method solves these issues.

Using a for-loop – Example # 1

See the Pen Array.prototype.map – Challenge – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Our first pass at this solution employs a for-loop. As mentioned above, this introduces a few problems. We have the “i” variable, for instance, which in this example is a global. In a real-world situation, however, we would want to put this code in a function so that the “i” variable does not wind up in the global scope. Also, the code in our for-loop is tedious. We need to use the “i” variable to keep track of the currently iterated rawNumbers element. There’s definitely a better way to go about this.

Using the Array map() method – Example # 2

See the Pen JavaScript Array.prototype.find() – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 2, we use the JavaScript Array map() method to solve the problems discussed. We’ve passed an anonymous function to that method, and this anonymous function takes the currently iterated number as its first argument. Inside of our function, we have some simple code that rounds the currently iterated number.

The biggest benefit to using the JavaScript Array map() method is that we no longer have the “i” variable or the for-loop. This is already a major improvement, especially the reduction of code, since it means that it’s simpler and easier to read. These are not minor details, and if this is a task that occurs multiple times in your application, you’ll soon find that the benefit gained by reducing repetitive code will quickly become significant.

Passing a function to the Array map() method – Example # 3

See the Pen Array.prototype.map – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The approach in Example # 3 is similar, but there’s one big difference: instead of passing an anonymous function to the Array map() method, we pass to the Math.round method, which makes our code even easier to read. This is largely because we leave the implementation details to Math.round and eliminate even more code: our anonymous callback function. There are two reasons that we can do this: Math.round takes a number to round as its first argument, just like our anonymous function, and it returns the rounded number, just like our anonymous function. Simplified code is better code and in this case, we have Math.round to thank for that.

Introduction to the JavaScript Array find() method

Array.prototype

JavaScript - find methodJavaScript’s Array find() method allows you to find the first element that matches logic provided by you.

When you have an array of values, it’s likely that you might need to find an element in that array. In particular, you might want to know which element in this array meets a certain criterion. Well, the criteria are up to you. For example, if your array contains numbers, you may want to know how many of the elements in that array have a value higher than a certain amount. Well, in this article I’ll demonstrate the JavaScript Array find() method, which provides a straightforward way to confront this problem.

Iterating an array usually requires counting. This makes sense, because in order to “do something” with every element in the array, you have to know how many elements are in there (i.e. the array’s “length”). Then you have to keep track as you count up to (or down from) the length of the array. This approach is perfectly valid, but it comes with problems.

The first problem is that setting up a loop of any kind creates boilerplate code, then you need a counter (i.e. “i” or “j”), and finally, you need logic that uses the value of your counter to determine whether or not your target elements have been found. Just discussing this in a “pseudocode” context is tedious, and writing the actual code is even more so. But the JavaScript Array find() method solves this problem, as it removes the need for tedious boilerplate code.

Using a while-loop – Example # 1

See the Pen Array.prototype.find() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

The tedious boilerplate code we discussed above is exactly what you find in Example # 1. We’re using a while-loop to iterate over the someNumbers array. On each iteration of the loop, we use the value of “i” to examine the currently iterated array element and determine if it meets the criteria for our search. This code is valid and it works, but it’s less than optimal.

Using the Array find() method – Example # 2

See the Pen Array.prototype.find() – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 2, we use the Array find() method to eliminate the problems introduced in the previous example. We’ve passed an anonymous function to the Array find() method, and this method takes the currently iterated element as its first argument. Inside of this anonymous function, we provide some logic that determines the currently iterated array element, then we decide whether or not it meets the criteria for our search. The first big benefit here is that we’ve removed the “while” loop. Also, we no longer have the “i” variable. These may seem like small details, but every variable takes up memory, and has scope.

As we know, JavaScript scope is controlled by functions, or blocks. So, for any variable we use, we need to either create a function to control its scope, or carefully initialize that variable in the right function. So the main benefits of the Array find() method are the simplified syntax in which verbose boilerplate code has been removed, and working with our more elegant JavaScript, which is easier to follow.

Introduction to the JavaScript Array filter() method

Array.prototype

JavaScript array filterWith the Array filter() method, you provide a function that returns an array containing the “filtered” elements. It is within this function that you provide the logic that determines how your original array is filtered.

Sometimes you have an array, but want to reduce the number of elements you work with, based on a certain logic. For example, you may have an array with the days of the week, but you only want to work with the days that start with the letter “T”, which means that you only want the elements “Tuesday” and “Thursday”. Well, JavaScript’s Array filter() method provides a simple and elegant interface by which you can solve this problem. In addition to the straightforward syntax, the Array filter() method eliminates the need for boilerplate code such as a for-loop. To further explain, we’ve demonstrated this in the code examples that follow.

Using a for-loop to filter an Array -Example # 1

See the Pen Array.prototype.filter- Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 1, we use a “while” loop to iterate the word’s array. “While” loops are perfectly valid in JavaScript, but they always make me nervous, because whenever I’ve started to use a “while” loop, I immediately ask myself: “is there a better way to do this?” The main reason is that with a “while” loop, if you’re not careful and your “while” logic is faulty, the loop could theoretically run forever. This is a bit off-topic, but I just like to point out that it’s important to use “while” loops with care.

Back to Example # 1. Inside of the “while” loop, we use the value of “i” to determine if the current word should be pushed to the “shorter” array or the “longer” array. Once this loop has completed, we update the UI to show the number of “shorter” and “longer” words. Again, perfectly valid code, but kind of verbose and less than optimal.

Using the Array filter() method -Example # 2

See the Pen Array.prototype.filter – Solution # 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 2 is a major improvement over the previous code. We leverage the Array filter() method to determine the number of “shorter” and “longer” words. There are a couple of areas of improvement here.

First, we’ve removed the need to manually push words to the “shorter” and “longer” arrays, because of the simple syntax of the Array filter() method. Notice that as we create the “shorter” and “longer” arrays, we assign the value by executing the Array filter() method. We provide an anonymous function to the Array filter() method, and the logic is simple: the sole argument passed to that anonymous function is the iterated word, and inside of the function we simply determine if the word’s length is greater than or less than five.

Second, we’ve removed the “while” loop. This is a major improvement, given the fact that it reduces the amount of code, but also since there is no longer any possibility that our code will run forever because of the use of a “while” loop.

Passing a function to the Array filter() method – Example # 3

See the Pen Array.prototype.filter – Solution # 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

The winsPrize() function approach of Example # 3 differs a bit. Instead of using an anonymous function when executing the Array filter() method, we pass a function declaration. Also, we’ve chained the Array filter() method off of an array literal (in other words: we create the array and then immediately execute the filter method). This is not necessarily a “more correct” approach, it’s just less verbose. The logic of the winsPrize() function is similar to the code in Example # 2. The main difference is that we pass a function declaration instead of an anonymous function.

JavaScript Template Literals – Basics

JavaScript

JavaScript LogoTemplate Literals introduce a new syntax into JavaScript. The backtick character provides a way to have placeholders as well as multi-line text without special characters.

Working with strings is a daily activity for most JavaScript developers. One of the most common challenges is dealing with multi-line text. This is not an unsolvable problem, but it can certainly be painful. In this article, I’ll demonstrate how Template Literals can be used to make working with multi-line text much easier. Also, I’ll demonstrate how to use placeholders with Template Literals.

Double and single quotation marks are the way that we have always worked with strings in JavaScript. Either approach works fine; you just need to be mindful of some restrictions. For example, with valid JSON, all properties must be in double quotes. Also, backslashes must be used to escape double and single quotes, depending on which one is in use. But now we have Template Literals, which introduce a new character: the backtick. When using the backtick, you can include line breaks in your text and they will be respected when your text is rendered. You can also use the newline character: “\n”. When using the newline character, you can “programmatically” insert a new line in your text without literally doing so.

Using HTML to create new lines – Example # 1

See the Pen YeYmNb by Kevin Chisholm (@kevinchisholm) on CodePen.

For Example # 1, we’ve taken the “old school” approach: we have created text using single quotes, and used the BR HTML element to create new lines in our text. When you look at the UI for Example # 1, you see that the new lines were created just as expected. We also use string concatenation to combine the “firstPart“, “endpart” and “author” variables. This is all fine, and I can say I’ve employed this approach thousands of times. The drawback with this, however, is the need to use the BR HTML element to create new lines in our text. It works as long as we actually render the HTML in our browser, but what about a situation in which the text will be rendered in a non-browser context?

Using Template Literals – Example # 2

See the Pen JavaScript Template literals – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Well, you’ll notice a dramatic difference in how we do things in Example # 2. Here, we’ve used Template Literals — specifically, the backtick character, to create our string. In doing so, we were able to include line breaks simply by literally using new lines in our text. You may have noticed that I’ve used a textarea HTML element to display the text, because, if I were to use a paragraph element, you wouldn’t see the line breaks. And this is because the paragraph element would simply render all of the text inside of itself. But by using a textarea HTML element, we can see that the line breaks have been preserved.

Now in Example # 2 you’ll see that there’s another new concept in play: the placeholder. On Line # 21, we create the “allText” variable, which contains the combined text contained in the “firstPart“, “endpart” and “author” variables. But instead of using string concatenation (as we did in the previous example), we use placeholders. The placeholder syntax is simple: you use a dollar sign and curly braces. Inside the curly braces, you can insert any valid JavaScript expression, which will be evaluated. In our example, we use this placeholder syntax to combine the “firstPart“, “endpart” and “author” variables.

Using the New Line Character – Example # 3

See the Pen JavaScript Template literals – Solution 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 3 is identical to the previous one, with one exception: we use the newline character instead of literal new lines. The output here is exactly the same, but the method for creating the string is different. This is not necessarily a “better” or “more correct” way of doing things; it’s simply an alternative way to create new lines in your string literal. The advantage here, of course, is that the new lines are created programmatically. For example, if you had a function that generated this string, based on some dynamic logic, you might want to include a single line break or double line break, depending on the logic. The newline character makes this kind of task much easier.

JavaScript Object Literal Shorthand Syntax Basics

JavaScript

JavaScript object literal shorthand syntaxJavaScript Object Literal Shorthand Syntax is a feature that provides a path to cleanerJavaScript. Not only does it provide a way to reduce the size of your code, but it will be easier to read and understand.

Many ECMAScript 2015 features provide improved ways to solve problems. Object literal shorthand syntax is a bit unique in that it’s not so much a shiny new tool, but an improved syntax. Now it might be tempting to dismiss this kind of feature as less-than-stellar, but it’s worth working into your routine for a number of reasons. For example, an improved syntax can lead to less code, and not only that, the code you write can be easier to understand. And believe me, those who inherit your code will thank you for this. So, in this article, I’ll explain how to use object literal shorthand syntax when defining properties and methods.

Typical Object Literal Syntax – Example # 1

See the Pen JavaScript Object Literal Shorthand Syntax – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

Let’s start with the way we’re used to working with object literals. In Example # 1 we have a getGoods() method that returns an object. The value argument is used on execution to set the value property, and the lowerValue() and raiseValue() methods lower and raise that value property. So this is all fine and everything works exactly as expected. In fact, if you look at the UI, the text that you see shows that our methods set and value property accordingly. Unlike many of the examples in this blog, there is nothing to “fix” here. Our code works fine and follows a typical syntax pattern because, as stated, I mainly wanted to establish that this is the way we normally work with object literals.

Object Literal Shorthand Syntax -Example # 2

See the Pen JavaScript Object Literal Shorthand Syntax – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, in Example # 2 we do things quite differently. To start, look at Line # 3. When we set the value property, there is no colon; we simply assign the value of the “value” argument that was provided when the function was executed. This syntax is concise, thereby requiring you to write less code. Now it may seem like a very small savings here, but when you have an application with many thousands of lines of code, the savings quickly add up.

Okay, so next, look at where we define the lowerValue() and raiseValue() methods. Here, notice two things are missing: there is no colon, and we don’t need the function keyword. We simply provide the parentheses and the curly braces (as well as the code inside the curly braces). Here, too, the savings may seem small on a per-line basis, but in a large application, the difference will be dramatic. And the additional benefit, especially when defining methods, is that the code is a bit easier to read.

Introduction to JavaScript Default Parameters

JavaScript

JavaScript default parametersJavaScript functions can take arguments, but they are optional by nature. Default parameter syntax makes it easy to determine if one or more arguments have been provided and if not, initialize them.

While something like Typescript can make it easier to enforce certain practices, use is voluntary. Ultimately, you can’t force a consumer to provide one or more arguments to your function. There are ways to work around this problem, but solutions are not simple. As is often the case, for example, solutions sometimes introduce new problems. There’s good news on this front, though, and in this article, I will demonstrate the JavaScript default parameter syntax and how it solves the above-mentioned problem.

The JavaScript default parameter syntax is surprisingly simple; instead of specifying an argument in the parentheses, you initialize it. This may look a bit deceiving, and, in fact, some may think that by doing this you are absolutely setting that value. But quite the contrary: what you are saying is: “If argument X is not provided, then initialize it and set it equal to this value.” So, you’re providing a “default” value for that argument, and if that argument is provided when the function is executed, then the provided value is used.

Example # 1

See the Pen JavaScript Default Parameters – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 1, the addBonus() function takes one argument: “bonus.” In that function, we had to write code that checks to see if the “bonus” argument was provided. If it was, then we use the provided value. Now, this code works just fine, but there’s a problem. If we accept this solution, that means that we’ll write code that is virtually identical to it any place else in our application where the same problem needs to be solved. So, of course, it’s worth remembering here that any time we have repeated code, we know that there’s a better way to solve a problem.

Example # 2

See the Pen JavaScript Default Parameters – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, when you take a look at the approach in Example # 2, you’ll see an immediate improvement. We’ve leveraged default parameter syntax so that the “bonus” argument is now optional, thereby creating the biggest advantage of this approach, which is that there is no longer any repeated code. By simply initializing the “bonus” argument, we ensure that if not provided, that variable will have a value.

Node.js File Uploads with Multer

Node.js

Node.js LogoWhen it comes to the UI, file uploads are pretty simple. But on the back-end, there is some work to do. Multer is a Node.js module that simplifies this process.

Uploading a file is a common task for Web applications. Today, most Web pages leverage AJAX — which requires JavaScript — for a smoother user experience, but this can be accomplished using only HTML and zero JavaScript. The truth is, HTML-only file uploads have been possible for more than 20 years. I mention this to point out that in the browser, file uploads are simple and require only a small amount of HTML. This is only half of the equation, however, because a file upload is useless without some back-end code that can process the file. So, in this article I’ll show you how to process a file upload in your Node.js application. To simplify the back-end code needed to handle a file upload, we’ll leverage Multer, a Node.js middleware for handling multipart/form-data.

For this article, our working example code is a simple Node application that accepts a POST request with an “enctype” of “multipart/form-data.” When the user uploads a file, our back-end code will take the uploaded file and put it in the “uploads” folder, right within the root of the project folder. Nothing too fancy here, but it’s worth noting that the examples provide plenty of opportunities for copy/paste. What you do with these examples is up to you, but at least you’ll know how to process a file upload in your Node application.

index.html

In the above example (index.html), we have the HTML file for our application, so take a look at the form element. You’ll see that the “enctype” attribute is set to “multipart/form-data,” which means that we will send images in various formats. This is also important to keep in mind because Multer will only process this kind of file-upload. Note also the input element, which has a type attribute of “file.” This ensures that the browser will take care of implementing a file-upload interface. So, in other words, there will be a “Choose File” button, which allows the user to select a file from his or her hard drive. We certainly don’t need to put any effort into this; simply setting type=“file” takes care of all of it. There is also a name attribute for this input element. This attribute is required so that Multer understands how to handle the request. The Submit button will pass the form to the same exact URL because there is no “action” attribute, so the default behavior is: this is the form submitted to the same exact URL.

Configuring Multer – Example # 1

Example # 1 contains all of the code for our Node application. For this project, we leverage the Express framework. By using Express, we significantly reduce the amount of code needed. One of the most powerful features of Express is the ability to easily create middleware, which is a perfect context for Multer because it needs to intercept the HTTP request for us. The upload variable is used to provide configuration for Multer. In this case, for example, it lets Multer know that we want our uploaded files to be placed in the “uploads” folder. We’re using express.static in order to serve the HTML and CSS files to the user, so when the user goes to the “/” route, index.html and style.css are served by the Express framework.

Adding a Handler for the POST route

On Line # 11, we set up a handler for the POST route. If you’ve ever used the Express framework when building a Node application, this pattern should look familiar to you. But notice that the second argument passed to the app.get() method is upload.single(‘img’). We’re using the upload variable created earlier. The single() method takes a string as an argument, which is the “name” attribute of the form field containing the uploaded file. For demonstration purposes, we output req.file to the console so we can see information on the uploaded file. We call the send method of the response object, passing it some HTML, which simply informs the user that the upload was successful and allows that user to go back to the “/” route.

At this point, it would be a good idea to run the example code yourself, so just follow these steps:

  • git clone
  • git@github.com:kevinchisholm/video-code-examples.git
  • cd /node/file-uploads-with-multer/
  • npm install
  • node index
  • Open this URL in your browser: http://localhost:3000/

Now in your browser, click the “Choose File” button and browse your hard drive for a file to upload. Once you’ve selected a file, click the “Submit” button. You should see the message: “File upload succeeded.” Now, if you look in the “uploads” folder in the root of the project folder, you should see a file with a name similar to: “08e36ff4c9d3dc106e3a9fa2367797c9”.

So, we’ve made good progress here; our example code works and we’re able to upload a file. As you can see, though, the original name of the file is not preserved, and a GUID-like name is provided. This can be helpful in that users will not overwrite a file when uploading the same-named file more than once. The downside, however, is that there’s no connection between the original file name and the one provided. So, let’s fix that.

Show the Original File Name – Example # 2

Stop the Node application and then start it again, using the second example: node index2. Now, upload a file again.
You’ll see that the original file name is preserved.
In Example # 2, we accomplished this by leveraging multer.diskStorage(). When calling that method, we provided a configuration object. The destination property told multer.diskStorage() where the uploaded file will go, and the filename property provided a way for us to specify what the name of the uploaded file will be. This method receives a second argument called file, so we use the “originalname” property of this object to set the file name. But there’s a new problem now: the user can overwrite an uploaded file by uploading a file with the same name. So let’s fix that.

Create a Dynamic File Name – Example # 3

In Example # 3, we have expanded the anonymous function passed to the filename() method. What we’ve done here is use regular expressions to extract the name of the file with and without the extension. We use Date.now() to generate what is essentially a unique value, and we piece the new file name back together. As a result, the user can upload the exact same file over and over, but each uploaded file name will be unique. For example: original-file-name_123456.jpg. So, let’s just confirm this. Stop the Node application and then start it again, using the third example: node index3. Now, upload the same file over and over. You’ll see that each uploaded file has a unique name, but the original file name is included so that it’s easy to reference the actual file that was uploaded.

mapbox-gl Uncaught ReferenceError: t is not defined

Mapbox

JavaScript LogoMy Mapbox integration was working fine locally. But then when did a Webpack build and pushed the assets to my web server, there was a JavaScript console error

I was implementing Mapbox in an Angular 4 application and everything was going fine. I was working locally, but after getting some UI issues worked out, things seemed to be going very smoothly. But when I ran my build and then viewed the static assets remotely, I had this lovely little JavaScript error in my console: “Uncaught ReferenceError: t is not defined“.

Hmmmm. everything seemed just fine to me. I did some troubleshooting and the issue looked like it was being caused by Mapbox. How could this be? It was not a problem locally.

I found the answer here: Build fails when using mapbox-gl webpack 2 and UglifyJSPlugin #4359.

Credit really goes to zezhipeng  – whose answer was spot-on. Seems that when Webpack parses the mapbox-gl module, things do not go too well. So I just needed to add this line to my Webpack config:

(the “” is just whatever else you have in your module.exports.module object.)

And that was it, working again. Thanks zezhipeng!