Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - module.exports "Module is not defined"

So, I am using RequireJS and React, trying to load a third-party component, which has been installed with:

npm install react-autocomplete

The structure is here: https://github.com/rackt/react-autocomplete/tree/master/lib

Now, I have a main.js file, initiated when requireJS is loaded, that looks like this:

require.config({
paths: {
      "react" : "react/react",
      "jsx-transformer" : "react/JSXTransformer",
      "react-autocomplete" : "node_modules/react-autocomplete/lib/main"
    }
});

require(["react"], function(react) {
    console.log("React loaded OK.");
});

require(["jsx-transformer"], function(jsx) {
    console.log("JSX transformer loaded OK.");
});

require(['react-autocomplete'], function (Autocomplete) {
    console.log("React autocomplete component loaded OK.");
    var Combobox = Autocomplete.Combobox;
    var ComboboxOption = Autocomplete.Option;
    console.log("Autocomplete initiated OK");
 });

Now, it all loads OK, but the third require statement throws a "module is not defined", for the main.js file in the third-party component, which looks like this:

module.exports = {
  Combobox: require('./combobox'),
  Option: require('./option')
};

I've been reading about that this has to do with me trying to require a CommonJS-style module, but I can't figure out how to fix it on my own, as I'm new to this.

Does anyone have a clear example on how I could get around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

RequireJS cannot load CommonJS modules as-is. However, there is a minimal modification you can make to them to load them. You have to wrap them in a define call like this:

define(function (require, exports, module) {

  module.exports = {
    Combobox: require('./combobox'),
    Option: require('./option')
  };

});

If you have a bunch of modules you need to convert, or if you are using a third-party library written in the CommonJS pattern and want to convert it as part of a build process, you can use r.js to perform the conversion for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...