How to use Dropzone with Webpack

How to use Dropzone with Webpack

As with most visual JavaScript libraries there are two sides to the story: getting the JavaScript code in your project, and getting the CSS code. Let’s start with JS.

Add dropzone as a dependency to your project:

$ yarn add dropzone

In your html, make sure you have an element that will act as the dropzone:

<!-- Head of your HTML file -->
<form action="/target" class="dropzone"></form>

JavaScript

Somewhere in your JavaScript code, you simply need to import it:

import Dropzone from "dropzone";

// Make sure Dropzone doesn't try to attach itself to the
// element automatically.
// This behaviour will change in future versions.
Dropzone.autoDiscover = false;

let myDropzone = new Dropzone("#my-form");
myDropzone.on("addedfile", file => {
  console.log(`File added: ${file.name}`);
});

In order for Dropzone to find the #my-form the element must already exist. Either put your <script> import at the end of your HTML file, or use some sort of window.onload logic.

CSS

To get the styling of Dropzone, I recommend you use the style-loader and css-loader libraries:

$ yarn add --dev style-loader css-loader

You then need to use these plugins in your webpack config:

module.exports = {
  // ...your config...
  module: {
    rules: [{
      test: /\.css$/,
      use: ["style-loader", "css-loader"]
    }]
  }
};

This allows you to import .css files which will be added to the content of the page.

Then simply import the CSS file somewhere in your code:

import "dropzone/dist/dropzone.css";

You can check out the full documentation :

https://dropzone.gitbook.io/dropzone/getting-started/installation/webpack-recommended