简体   繁体   中英

NPM modules in Grunt based projects

Node has a simple module loading system which uses require() method call to load modules from different locations in the root folder. Eg

var qr = require('qr-image');    

I am trying to do something similar in grunt but i am unsuccessful with that.

I had added this module to package.json file in the following fashion and then ran npm install at root directory of the project.

"devDependencies": {
    .
    .
    .

    "qr-image": "^2.0.0"
}, 

Now whenever I use require I get the following error on console and my code breaks.

ReferenceError: require is not defined

Please suggest as how to use the npm module in Grunt based project, Thanks.

The require function isn't available in web browsers. Instead it's part of nodejs, which is a server-side language (eg, something you might run directly from your computer terminal, not in a browser) and used to load dependencies in that language.

In a web browser, I usually just include my dependencies as additional scripts on the page, eg,:

<script src="path/to/my/dependency.js"></script>
<script src="path/to/my/code.js"></script>

Some other options are RequireJS or what's listed in this question or as more of a general purpose dependency manager for front-end code: Bower .

Looking closer at your question, it's likely that the "qr-image" npm dependency won't work in client-side code for you (since it was built to run via node in server-side code).

A quick search for QR code client-side code brought up this SO post , which points to the QRCode.js project for client-side QR code generation—I haven't used it, but it looks like a step in the right direction for what you're working on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM