How you can make a progressive web app in an hour

Progressive Web App’s use local service workers to load instantly, regardless of the network state. Image source: developers.google.com/web/progressive-web-apps

In this quick tutorial, I’ll show you how to add your HTML, Javascript, and styling to this template to create an app that works online, offline, in a browser, and as a mobile app

Progressive web apps are a hybrid of a website and an app that you might use on a tablet or mobile. Making one has a lot in common with creating a website, but with a few key extra files and concepts involved. It need not take a week of trial and error or trawling through a tutorial to get one up and running.

This post will show you how to make one in an hour that you can then host, use online as a website, and use offline and as a mobile app.

To give an example of what you could create, here is an example of one I made earlier based on Google’s codelab on web apps. It generates a QR code from the text you enter.

qr-code-pwa.firebaseapp.com

Some key feature of Progressive Web Apps:

Responsive — Fits any form factor: desktop, mobile, tablet, or whatever is next.
Connectivity independent — Enhanced with service workers to work offline or on low-quality networks.
Installable — Allows users to add apps they find most useful to their home screen without the hassle of an app store.
Linkable — Easily share the application via URL, does not require complex installation.

Use a template to start your app

To get started, clone this template repo (or just copy the bits you need). This includes the website project structure with everything you need to make an app.

├── README.md
├── firebase.json
└── public
    ├── fonts
    │   └── roboto
    │       └── ...
    ├── images
    │   └── icons
    │       └── ...
    ├── index.html
    ├── manifest.json
    ├── scripts
    │   ├── app.js
    │   ├── jquery-3.3.1.js
    │   └── materialize.js
    ├── service-worker.js
    └── styles
        ├── materialize.css
        └── style.css

What’s included in the template project

  • JQuery: A library for supporting JavaScript on your website
  • For styling and a range of quick to use components and effects, this has materialize.js and CSS from materializecss.com. Remove or replace it if you prefer something different.
  • public/service-worker.js: Service Workers allow you to run your app offline, as well as other innovative things. Currently, this will cache the app’s files for quick local access. Read more about this in Google primers: service-workers.
  • public/manifest.json: A JSON file specifies how your app appears to the user in the areas where they would expect to see apps (for example, the mobile home screen). It also directs what the user can launch, and more importantly, how they can launch it. Read more about this here.

Adding your code

The main files to edit are:

  • public/index.html: The main HTML page for your app. Currently it has title nav bar, a card, an input field for a message, and a button to display this on the card.
  • public/scripts/app.js: This contains the JavaScript to handle the logic in your app. It currently uses localStorage for storing data when the user clicks the button, and it is recommended to use another database in production, such as indexedDb (Read more here).
  • public/style/style.css: Add your own styling to this file.

Once you’ve made your app:

  • Update the list of your app’s files to cache in service-worker.js
  • images/icons: Create square icons of the number of pixels for each size and save them here. These will be used by browsers and operating systems.

Troubleshooting

If you are using the Chrome browser on a Mac, bring up the Dev Tools window:

  • View → Developer → Developer Tools

The Console tab will show you the logs from the app. On the Application tab,you can see the data stored locally.

  • Storage → Local Storage shows you the message stored by the app.
  • Cache → Cache Storage → template-pwa displays the files you have set to cache and retrieve from within service-worker.js

If you encounter problems, it’s often worth switching the service worker off and on again, then clearing the cache and reloading the app.

Also, see:
– Google Codelabs — your-first-pwapp
– How to debug Progressive Web Apps using Browser Developer Tools by Flavio Copes in freeCodeCamp

Using your app

Now try it out!

You should be able to visit the hosted app in your browser, and add it to your home screen on your mobile!

Here’s one I made earlier: qr-code-pwa.firebaseapp.com

Read more from ryanwhocodes

Mimecast acquires Ataata

Mimecast acquired Ataata laying the ground work for the most effective cybersecurity awareness training program imaginable.

The acquisition enhances Mimecast’s offerings, adding cybersecurity awareness training, risk scoring and real-world simulation attack scenarios to your already potent mix of cyber resilience services.

What Is Ataata?

Developed by top leadership from the U.S. military, law enforcement and the intelligence community, Ataata is a security awareness training and cyber risk management platform that helps you combat information security breaches caused by employee mistakes.

Ataata combines effective, modern training techniques with predictive analytics to solve for your company’s vulnerability to human error. Human error is involved in 95% of all security breaches. But humans are maddeningly careless and resistant to change. Employees’ casual mistakes lead to disaster all the time — and cost people their jobs. To change security culture effectively, employees have to know what to do, care enough to improve, and then do what’s right when it matters.

Creating a web app as side project

About the process of building my personal little side project 1tuner.com 📻

1Tuner is a progressive web app that you can use to listen to online radio. And it allows you to plan your own ideal radio listening day, so the player switches between radio streams automatically.
The app is pretty basic, but it changed while I was learning during development of it. In this article I will try to describe the process and decisions.

The “problem”

At the office, we always listened to good-old radio. For years, we tuned our browser to the audio stream of the Dutch public radio channel 3FM. We heard nice pop/rock tunes, some fine jocks and a good news service.
Then came our problem, jocks left the station, and a music format switch brought us shittier music (and OK, a better logo maybe). At the same time, the dusty Dutch Radio 2 was changing as well — for the better in our opinion (reluctantly admitted at first). We were also looking for other alternatives. In the end, we switched throughout the day to Radio 2, to 3FM, to Radio 2 etc…

I knew this had to be fixed. So I started a new web app to start Radio 2.5; an automatic stream switcher.

Where to start

I was fairly late to the “front-end framework party”, and wanted to dive in. This side project seemed ideal for that. I started with Vue.js, and wanted to try Webpack as well. I found some basic boilerplate projects and started by trial and error. Lots of errors actually… The thing with side projects is: time. I’m not sure how other people manage this, but to be fair it’s hard to start up each time when you leave your code behind for some days. And when you finally found out where you got stuck, it’s time to sleep! 🙄 I was struggling in the world of Webpack modules and loaders, and somehow corrupted npm modules.

Another confusing problem at first, was the audio element. Initially I used the “autoplay” attribute, and then just changed the audio source. This worked in Chrome on desktop, but not on mobile — audio didn’t play on mobile.
It took some time before I understood this was an “autoplay” problem (later on, the autoplay behaviour was the same on desktop).
From my experience; just avoid using autoplay 🙂. Nowadays you also should trigger audio change on user gestures like the tap/click of a button.

Start over

Once I had a basic app that was switching the audio streams, I was done with it for some time. But I also read a lot about Preact, and when preact-cli came by in my Twitter timeline, I wanted to try that! So I started from scratch. Or maybe not really, because preact-cli works like a charm right out of the box.

One thing that bothered me with my previous setup was file size and loading times. I was using Firebase as well, which was actually quite big (with all the bells & whistles). And together with all inefficient things I had included, the total (optimized & minified) size was ridiculous — because I was just tinkering around.

The fresh start with Preact was also reason to keep things more efficient. Finally, I came to the conclusion that I needed to keep things as simple as possible. So no more authentication and saving to Firebase, but save all user data locally, and use the power of URL’s! Progressive web apps rock! 😎

UI / Design

OK, don’t laugh. I really thought things through. I wanted an interface that was as clean as possible, because the main way to use the app would be to tap and listen.

Icon
The main branding would be the app icon. But I still had to choose a name and register a domain. First it was stream-zapper, stream-switch, tunar, stream-tune… I ended up with 1tuner.com. One advantage of the name is that it’s on top at your app list/drawer when it’s sorted alphabetically. 😉

Progress in icons

For the logo and icons, I used the online vector tool Gravit Designer — it’s free and pretty amazing actually. Open, edit and save to SVG.

Fonts
Because I wanted a quick loading and a native-like app experience, I wanted to go with system fonts. By using system fonts, you always get the default font of the device. Stuart Frisby wrote a nice article about implementing system fonts on Booking.com.

Layout
I started with a default header menu and a play button on the main screen. Then I moved the play button to a fixed positioned footer.
Recently I moved the navigation to a fixed icon/tab bar for mobile and left-hand menu for bigger screens. For web apps, the tab bar navigation can be problematic because in some browsers you get a double navigation at the bottom (app + browser navigation). But overall the experience is better this way I guess.

PWA features

I use the Media Session API to display the current playing radio station notification. Obviously this puts in the “progressive” part in the web app, as this only seems to be supported in Chrome on Android right now. However, it works out great; you’ll see the logo with play/pause on your lock screen, and even on your smartwatch!

The Media Session API gives the web app a “native app feel”

As you may have noticed there is only a “pause” icon. Because in the 1tuner app you are listening to “live” radio, I handle the pause event as “stop”. Unfortunately, there seems to be no stop event/icon from the media notification right now.

The Web Share API is another great addition to the app. It’s easy to use and directly opens up the native share menu when you click the share icon.

Other

  • Navigator.languages/language for the default “Region” filter.
  • I use idb-keyval from Jake Archibald, a simple way to store key/value data that is implemented with IndexedDB.

Tools, services & resources

It’s just so great that there are so much free tools and services!
Yes, I‘m Dutch. 😁 An overview:

  1. Visual Studio Code is awesome to use with the integrated terminal, together with preact-cli and live reloading. 👍
  2. Preact-cli is amazing, you can start with some demo projects, routing, pre-render and a service worker that just works out of the box. Preact is like React, but smaller! Big thanks to Jason Miller.
  3. I used the online vector design tool Gravit Designer for the logo and icons. You should really try this out!
  4. Gravit Designer easily exports to SVG, but the output can still be optimized. If you don’t have it automated in your project, you should use the excellent SVGOMG from Jake Archibald.
  5. To get all the app icons: https://realfavicongenerator.net. It’s pretty full featured as you even get a Safari Pinned Tab SVG traced icon for instance. You can also use the favicon generator API and use this in your own automated tasks.
  6. I use Firebase for hosting and the database. I don’t use much of the other features anymore, but authentication for client-side apps is really easy with Firebase!
  7. The header image is from Pexels, a free stock photo library (CC0 license).

Upcoming versions

Besides debugging and adding more radio stations, I have a couple more ideas that I would like to add to the app;

  • Let users add radio stations.
  • Share planning with timezone support. Had a quick look earlier, but this is a bit complex because of daylight saving times.
  • Podcast support (also for use in the planner).
  • An option to cast to Chromecast directly.

Thanks

❤ Rianne

🙂

How to Build Your Own “Spotify Model”

It is early 2011 and you are the CTO of Spotify. You’re staring out of the window of a coffee bar in a snowy and dark Stockholm. It has been an amazing year. Your company is acquiring customers faster than ever and you’re launching in more and more countries. However, Google and Apple are catching up. It’s not a question if they will launch their own music streaming services, but when. To survive that eventuality Spotify must become a truly global player.

You have to do this while still figuring out how the music streaming business actually works. What do customers really want? What will they pay for? What do you need to do to convince someone to stop buying CDs or MP3s and instead be willing to pay for a monthly streaming subscription?

“We need to innovate, experiment and learn faster than the competition.”

To do all this on a global scale you have to grow your engineering team. It has been a huge challenge to grow your team from 10 to 100 in the last year. Some people predict you might even need to attract another 1,000 engineers to pull this off. You feel overwhelmed. How can you attract the right talent with the right mindset across the entire globe?

Managing a team of 100 is already complicated. But if you grow even further, how do you stay agile? How can you keep the start-up culture that has brought success so far and prevent becoming a lumbering bureaucracy?

Spotify’s organization design

Another two years have passed and the company now has 15 million customers. The engineering team has tripled in size to 300 people. A challenge that has been top of mind for a while now is, “With 30 teams, how do we make sure we build a castle that makes sense to the customer, instead of a pile of 30 bricks that nobody likes?”

The teams have started to experiment with a scaling model that uses Squads, Chapters, Guilds and Tribes who aim to implement ‘minimum viable bureaucracy’ and balance high autonomy with high alignment.

Source: Spotify’s engineering culture

This structure is just one piece of the puzzle, though. Through a few workshops, the agile coaches came up with a set of organizational design principles with the autonomous team as the core concept. This extension of the agile manifesto is called “Agile à la Spotify”, and has been printed on the walls across the office:

  • Continuous improvement: At Spotify, part of my work is to look for ways to continuously improve, both personally, and in the wider organisation.
  • Iterative development: Spotify believes in short learning cycles, so that we can validate our assumptions as quickly as possible.
  • Simplicity: Scaling what we do is key to Spotify’s success. Simplicity should be your guidance during scaling. This is as true for our technical solutions, as for our methods of working and organising the organisation.
  • Trust: At Spotify we trust our people and teams to make informed decisions about the way they work and what they work on.
  • Servant leadership: At Spotify managers are focused on coaching, mentorship, and solving impediments rather than telling people what to do.

Full autonomy is a trade-off

Fast forward to early 2018. Spotify has 140 million users in 61 countries. It has announced an IPO at a $20 billion valuation. Engineering and R&D is now 180 teams and 1,800 people. In total, Spotify employs over 3,500 people: the organization is no longer a startup, it’s a global enterprise.

A lot has gone really well. The culture is known for a high level of empowerment and trust, a focus on personal development, and is known for its sense of purpose. Teams are fully empowered to fulfill their mission and have the freedom to act independently. But as Joakim Sundén pointed out, it is far from an agile nirvana.

“What is the best thing about working at Spotify? What is the most challenging thing about working at Spotify? The answer for both questions is the same: Autonomy.” — Joakim Sundén

Managing 180 autonomous teams can feel like herding cats, especially when it comes to projects that span across teams.

Some recent examples: implementing SOX compliance to enable the IPO, keeping up with new privacy laws and moving all infrastructure into the Google Cloud. Also, the lack of focus on architecture and technical standards has made it challenging to scale the platform to support its growing user base.

Implementing these initiatives top-down wouldn’t work in Spotify’s culture. A team can simply say “I don’t want to do it” and would need to be seduced to give these priority.

Over the years, the lack of central planning and standardization has enabled hyper-speed, hyper-growth and hyper-innovation. But it has made certain things a lot harder that are easy for more traditional organizations.

“There is no right or wrong, it’s all trade-offs” — Henrik Kniberg

Time will tell how Spotify will continue to evolve. It’s a challenging balancing act between doing the right things, doing the things right and doing things fast.

Don’t copy the model

As agile organization designers, we’ve been following Spotify closely. Over the years, we’ve visited their offices several times. It’s an awesome company and there is much to learn from them. We love how the engineering culture videoshave inspired thousands of people to start upgrading their organizations.

However, if you’re considering implementing the ‘Spotify model’, please think again. Is your organization building a music player? Is your organization still trying figure out its business model? Is your organization facing hyper-growth? Is “move fast and break things” applicable to your product?” Maybe. But, probably not.

Source: xkcd

When people copy the ‘Spotify model’, it often happens through a top-down directive, without taking a close look at what kind of culture and leadership is needed to make it work. Often the existing hierarchy is changed into a new, static matrix blueprint (even if the matrix is labeled with Squads, Chapters, and Tribes), instead of growing a culture of continuous participatory change. This will inevitably make things worse. Even people who work at Spotifyrecommend to not copy their model.

Don’t get us wrong: in order to enable agility in an organization, we do recommend that you move away from top-down management and focus on empowering capable teams. But to copy a pre-existing model and believe that your problems will also be solved, is short-sighted and naive.

“The only Spotify way of working that actually works is turning on the Spotify volume really loud and dance.” — Erwin Verweij

Evolve your own organizational model instead

Just as startups are focused on finding product-market fit, we believe you should start on a journey to find your organization-context fit. Spotify has been able to do both.

We love this quote that is at the heart of what we believe:

“Stop trying to borrow wisdom and think for yourself. Face your difficulties and think and think and think and solve your problems yourself. Suffering and difficulties provide opportunities to become better. Success is never giving up.” — Taiichi Ohno

So what can you do if you want to gain agility, speed and innovation? Where to begin?

First, ask yourself, is there a clear picture of what issues you’re trying to solve with a new organizational model? If possible, find a few measurable indicators of what needs to be improved.

Involve not only your leadership team, but also a wide variety of people in the organization to gather ideas and co-create a picture of the desired future state. A good question to ask is: what is holding you back from doing the best work of your lives?

Don’t forget to appreciate what is going really well and decide what you definitely want to keep.

Take inspiration from a wide variety of future of work practices and companies. Look at different models of self-organization that fit different scale and risk contexts. Look beyond Spotify and even look beyond agile to gain org-wide agility.

Figure out what the main capabilities are you need to upgrade and where in the organization they are rooted. The OS Canvas is a useful tool for this exercise.

Design and start a number of pilots that help you try out new ways of working and allows you to quickly learn if it fits your specific context. Expand the pilots that show promise. End the ones that don’t produce the effect you’re looking for. Build your organization’s ability to constantly try new behaviors and learning from those experiments.

At the end of the day, use the Spotify model as an inspiration for what’s possible when you spend time and attention developing your own operating system — not as a model for what your own system may end up looking like. Design, test, and evolve your own model as inclusively as possible. Don’t do a big-bang change towards a new static target operating model, but instead build the muscle for continuous participatory change.

Don’t “do the Spotify model” — do your model.


Co-authored by a friend of The Ready: Roy Gielen (Agile enabler, trainer & coach at Ctree)


Ready to change how you work? The Ready helps complex organizations move faster, make better decisions, and master the art of dynamic teaming. Contact us to find out more. While you’re at it, sign up to get our newsletterThis Week @ The Ready delivered to your inbox every week.

Follow me on Twitter | Follow The Ready on Twitter | TheReady.com

A beginner’s introduction to Webpack

Psssst! I’m working on a Vue.js Course. Stay in the loop, sign up here and immediately get my Vue.js free ebook and soon the Vue.js Cheat Sheet!🔥

What is Webpack?

Webpack is a tool that lets you compile JavaScript modules. It’s also known as a module bundler.

Given a large number of files, it generates a single file (or a few files) that run your app.

It can perform many operations:

  • helps you bundle your resources.
  • watches for changes and re-runs the tasks.
  • can run Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.
  • can transpile CoffeeScript to JavaScript
  • can convert inline images to data URIs.
  • allows you to use require() for CSS files.
  • can run a development webserver.
  • can handle hot module replacement.
  • can split the output files into multiple files to avoid having a huge JS file to load in the first page hit.
  • can perform tree shaking.

Webpack is not limited to being used on the front-end, but is useful in backend Node.js development as well.

There are many predecessors of Webpack and lots of similarities in what those tools and Webpack do. The main difference is that those tools are known as task runners, while Webpack was born as a module bundler.

Webpack is a more focused tool. You just need to specify an entry point to your app (it could even be an HTML file with script tags) and webpack analyzes the files and bundles them in a single JavaScript output file that includes everything you need to run the app.

Installing Webpack

Webpack can be installed globally or locally for each project.

Global install

Here’s how to install it globally with Yarn:

yarn global add webpack webpack-cli

with npm:

npm i -g webpack webpack-cli

once this is done, you should be able to run

webpack-cli

Local Install

Webpack can be installed locally as well. It’s the recommended setup, because Webpack can be updated per-project, and you have less resistance in using the latest features just for a small project rather than updating all the projects you have that use Webpack.

With Yarn:

yarn add webpack webpack-cli -D

with npm:

npm i webpack webpack-cli --save-dev

Once this is done, add this to your package.json file:

{ 
  //... 
  "scripts": { 
    "build": "webpack" 
  } 
}

Once this is done, you can run Webpack by typing

yarn build

in the project root.

Webpack configuration

By default, Webpack (starting from version 4) does not require any config if you respect these conventions:

  • the entry point of your app is ./src/index.js
  • the output is put in ./dist/main.js.
  • Webpack works in production mode

You can customize every little bit of Webpack of course, when you need. The Webpack configuration is stored in the webpack.config.js file, in the project root folder.

The entry point

By default the entry point is ./src/index.js This simple example uses the ./index.js file as a starting point:

module.exports = {
  /*...*/
  entry: './index.js'
  /*...*/
}

The output

By default the output is generated in ./dist/main.js. This example puts the output bundle into app.js:

module.exports = {
  /*...*/
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  }
  /*...*/
}

Using Webpack allows you to use import or require statements in your JavaScript code not just to include other JavaScript, but any kind of file (for example CSS).

Webpack aims to handle all our dependencies, not just JavaScript, and loaders are one way to do that.

For example, in your code you can use:

import 'style.css'

by using this loader configuration:

module.exports = {
  /*...*/
  module: {
    rules: [
      { test: /\.css$/, use: 'css-loader' },
    }]
  }
  /*...*/
}

The regular expression targets any CSS file.

A loader can have options:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          }
        ]
      }
    ]
  }
  /*...*/
}

You can require multiple loaders for each rule:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.css$/,
        use:
          [
            'style-loader',
            'css-loader',
          ]
      }
    ]
  }
  /*...*/
}

In this example, css-loader interprets the import 'style.css' directive in the CSS. style-loader is then responsible for injecting that CSS in the DOM, using a <style> tag.

The order matters, and it’s reversed (the last is executed first).

What kind of loaders are there? Many! You can find the full list here.

A commonly used loader is Babel, which is used to transpile modern JavaScript to ES5 code:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
  /*...*/
}

This example makes Babel preprocess all our React/JSX files:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  },
  resolve: {
    extensions: [
      '.js',
      '.jsx'
    ]
  }
  /*...*/
}

See the babel-loader options here.

Plugins

Plugins are like loaders, but on steroids. They can do things that loaders can’t do, and they are the main building blocks of Webpack.

Take this example:

module.exports = {
  /*...*/
  plugins: [
    new HTMLWebpackPlugin()
  ]
  /*...*/
}

The HTMLWebpackPlugin plugin does the job of automatically creating an HTML file and adding the output JS bundle path, so the JavaScript is ready to be served.

There are lots of plugins available.

One useful plugin, CleanWebpackPlugin, can be used to clear the dist/ folder before creating any output, so you don’t leave files around when you change the names of the output files:

module.exports = {
  /*...*/
  plugins: [
    new CleanWebpackPlugin(['dist']),
  ]
  /*...*/
}

The Webpack mode

This mode (introduced in Webpack 4) sets the environment on which Webpack works. It can be set to development or production (defaults to production, so you only set it when moving to development).

module.exports = {
  entry: './index.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  }
}

Development mode:

  • builds very fast
  • is less optimized than production
  • does not remove comments
  • provides more detailed error messages and suggestions
  • provides a better debugging experience

Production mode is slower to build, since it needs to generate a more optimized bundle. The resulting JavaScript file is smaller in size, as it removes many things that are not needed in production.

I made a sample app that just prints a console.log statement.

Here’s the production bundle:

Here’s the development bundle:

Running Webpack

Webpack can be run from the command line manually if installed globally. But generally you write a script inside the package.json file, which is then run using npm or yarn.

For example this package.json scripts definition we used before:

"scripts": {
  "build": "webpack"
}

allows us to run webpack by running

npm run build

or

yarn run build

or simply

yarn build

Watching changes

Webpack can automatically rebuild the bundle when a change in your app happens, and it keeps listening for the next change.

Just add this script:

"scripts": {
  "watch": "webpack --watch"
}

and run

npm run watch

or

yarn run watch

or simply

yarn watch

One nice feature of the watch mode is that the bundle is only changed if the build has no errors. If there are errors, watch will keep listening for changes, and try to rebuild the bundle, but the current, working bundle is not affected by those problematic builds.

Handling images

Webpack allows you to use images in a very convenient way, using the file-loader loader.

This simple configuration:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      }
    ]
  }
  /*...*/
}

Allows you to import images in your JavaScript:

import Icon from './icon.png'

const img = new Image()
img.src = Icon
element.appendChild(img)

Where img is an HTMLImageElement. Check out the Image docs.

file-loader can handle other asset types as well, like fonts, CSV files, XML, and more.

Another nice tool to work with images is the url-loader loader.

This example loads any PNG file smaller than 8KB as a data URL.

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.png$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
  /*...*/
}

Process your SASS code and transform it to CSS

Using sass-loadercss-loader and style-loader:

module.exports = {
  /*...*/
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  }
  /*...*/
}

Generate Source Maps

Since Webpack bundles the code, Source Maps are mandatory to get a reference to the original file that raised an error. For example:

You tell Webpack to generate source maps using the devtool property of the configuration:

module.exports = {
  /*...*/
  devtool: 'inline-source-map',
  /*...*/
}

devtool has many possible values, the most used probably are:

  • none: adds no source maps
  • source-map: ideal for production, provides a separate source map that can be minimized, and adds a reference into the bundle, so development tools know that the source map is available. Of course you should configure the server to avoid shipping this, and just use it for debugging purposes
  • inline-source-map: ideal for development, inlines the source map as a Data URL

Psssst! I’m working on a Vue.js Course. Stay in the loop, sign up here and immediately get my Vue.js free ebook and soon the Vue.js Cheat Sheet!🔥


Originally published at flaviocopes.com.