import QRCode constructor for Javascript through webpack

Viewed 1865

I want to use the QRCode generator from this repo: https://github.com/davidshimjs/qrcodejs

How do I import the QRCode through webpack? When I installed qrcodejs through npm the index.js contained this code module.exports = 'qrcodejs'; When I use require('qrcodejs'); in my code it returns the string 'qrcodejs', but I want to import the QRCode constructor through webpack. I want to be able to call the constructor in my code like so, after importing it with webpack.

let qrcode = new QRCode("output", { 
                                    text: "http://google.com", 
                                    width: 100, 
                                    height: 100, 
                                    colorDark: "#188710", 
                                    colorLight: "#ffffff" 
                                  });

What do I have to do to accomplish this? I am using ES6 Javascript without any frameworks or other libraries, besides webpack.

UPDATE

index.js inside the qrcodejs folder

module.exports = {
    module: {
        rules: [
            { test: /qrcode/, loader: 'exports-loader?QRCode' }
        ]
    }
}

myproject.js

  import { QRCode } from 'qrcodejs'

export class EditProduct {

     openProduct(){
        let test = require('qrcodejs'); // returns the module object with the rules array
         let test2 = QRCode // returns undefined
     }
}
2 Answers

Use export-loader to make module.export = <anything you want>

basiclly what you want is to have qrcode.min.js module.export return QRCode.

You can define a rule for it:

module: {
  rules: [
    { test: /qrcode/, loader: 'exports-loader?QRCode' }
  ]
}

Just as Raz Ronen said, install export-loader.

This will allow us to introduce non-modular js to Webpack.

After installing add the QRCode module as:

import QRCode from 'exports-loader?QRCode!qrcodejs/qrcode'

based on the answer here

Related