简体   繁体   English

如何正确使用require.js要求节点模块?

[英]How to properly use require.js to require a node module?

So, I have no experience with Node or require.js. 因此,我没有Node或require.js的经验。 I know questions similar to this one have already been posted, but unfortunately, their solutions were no use in my case, sorry. 我知道已经发布了与此问题类似的问题,但是很遗憾,对我而言,他们的解决方案没有用。

So all I'm trying to achieve here is to use the random-words Node module in my app (client-side). 因此,我在这里想要实现的全部是在我的应用程序(客户端)中使用随机单词 Node模块。 After I have installed it with npm install random-words , I am trying to use this: 在使用npm install random-words安装它之后,我试图使用此功能:

var randomWords = require('random-words');  
console.log(randomWords());

but with no luck. 但没有运气。 I have been trying to get this to work for over 2 hours now, reading the documentation, watching tutorials, searching on Stack Overflow but I always get an error. 我一直在尝试使它工作超过2个小时,阅读文档,观看教程,在Stack Overflow上进行搜索,但是我总是遇到错误。 Right now, I am getting this output/errors: 现在,我得到以下输出/错误:

Require inside of index.html executed

    Uncaught ReferenceError: module is not defined
        at index.js:338
    (anonymous) @ index.js:338

    require.js:5 Uncaught Error: Module name "node_modules/random-words" has not been loaded yet for context: _. Use require([])
    https://requirejs.org/docs/errors.html#notloaded
        at makeError (require.js:5)
        at Object.s [as require] (require.js:5)
        at requirejs (require.js:5)
        at script.js:2
        at Object.execCb (require.js:5)
        at e.check (require.js:5)
        at e.<anonymous> (require.js:5)
        at require.js:5
        at require.js:5
        at each (require.js:5)

Here is my directory structure: 这是我的目录结构:

My App
|-- js
|   |-- script.js
|   `-- node_modules
|       `-- random-words
|           |-- tests
|           |   `-- test.js
|           |-- index.js
|           `-- package.json
|-- config.js
|-- index.html
|-- package-lock.json
`-- require.js

My code inside index.html: 我在index.html中的代码:

<script data-main='config' src='require.js'></script>
    <script>
    require(['config'], function(){
        require(['script']);
        console.log("Require inside of index.html executed");
    });
    </script>

My code inside config.js: 我在config.js中的代码:

requirejs.config({
    baseUrl: 'js',
    paths: {
        randomWords: 'node_modules/random-words/index'
    }
});

My code inside script.js: 我在script.js中的代码:

define(['randomWords'], function(){
                var randomWords = require('node_modules/random-words');
                console.log("Script.js code executed");
        });

Thanks in advance for any response/advice, I am getting really desperate and will not be able to move on until I get this to work. 在此先感谢您的任何答复/建议,我实在感到绝望,无法继续工作,直到我将其付诸实践。

通过使用Browserify而不是require.js解决

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

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