简体   繁体   English

基于Grunt的项目中的NPM模块

[英]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. Node具有一个简单的模块加载系统,该系统使用require()方法调用从根文件夹中的不同位置加载模块。 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. 我已经按照以下方式将此模块添加到package.json文件,然后在项目的根目录下运行npm install。

"devDependencies": {
    .
    .
    .

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

Now whenever I use require I get the following error on console and my code breaks. 现在,每当我使用require时,控制台上都会出现以下错误,并且代码中断。

ReferenceError: require is not defined ReferenceError:需求未定义

Please suggest as how to use the npm module in Grunt based project, Thanks. 请提出建议,在基于Grunt的项目中如何使用npm模块,谢谢。

The require function isn't available in web browsers. require功能在网络浏览器中不可用。 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. 相反,它是nodejs的一部分,它是一种服务器端语言(例如,您可以直接从计算机终端运行而不是在浏览器中运行的某种语言),并用于加载该语言的依赖项。

In a web browser, I usually just include my dependencies as additional scripts on the page, eg,: 在Web浏览器中,我通常只将我的依赖项作为其他脚本包括在页面上,例如:

<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 . 其他一些选项是RequireJS此问题中列出的内容,或者更多是前端代码的通用依赖项管理器: 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). 仔细研究您的问题,“ qr-image” npm依赖项可能无法为您在客户端代码中工作(因为它是通过服务器端代码中的node运行的)。

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. 快速搜索QR代码客户端代码出现了这个SO帖子 ,它指向QRCode.js项目,用于客户端QR代码生成-我没有使用过,但看起来像是朝正确方向迈出的一步您正在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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