Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import QRCode constructor for Javascript through webpack

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
     }
}
like image 712
Jiren Avatar asked Apr 19 '26 17:04

Jiren


2 Answers

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

like image 149
GEkk Avatar answered Apr 21 '26 07:04

GEkk


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' }
  ]
}
like image 25
Raz Ronen Avatar answered Apr 21 '26 07:04

Raz Ronen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!