Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading webpack module in a require.js based project returns null

I'm trying to load a library that compiles to Webpack in a require.js project. While the library exposes an object, it returns null when required from the require.js project :

define(function(require, exports, module) {
  [...]
  require("./ext/mylib.core.js"); // -> null
})

Is there any flags that I can use in Webpack to enable AMD compliance ? There are some references to AMD in the generated library but as it is it does not seem to do anything.

like image 927
fredericlb Avatar asked Oct 15 '15 11:10

fredericlb


2 Answers

The solution was in Webpack documentation : there is an outputLibrary flag that can be set to "amd" or "umd" and in that case webpack produces amd compliant modules.

like image 64
fredericlb Avatar answered Oct 04 '22 03:10

fredericlb


EDIT 3:/EDIT: 4 Webpack is not cooperating it may seem, so another possibility would be to expose the module with the shim config option:

require.config({
    paths: {
        // Tell require where to find the webpack thingy
        yourModule: 'path/to/the/webpack/asset'
    },
    shim: {
        // This lets require ignore that there is no define
        // call but will instead use the specified global
        // as the module export
        yourModule: {
            exports: 'theGlobalThatIsPutInPlaceByWebpack'
        }
    }
});

This obviously only works in the case that the webpack stuff is putting something in the global scope. Hope this helps!

EDIT 2: So I got the question wrong as pointed out in the comments. I didn't find any built-in functionality to produce AMD modules from webpack - the end result seems to be a static asset js file. You could wrap the result in a

define(function () {
    return /* the object that webpack produces */;
});

block, maybe with the help of some after-build event (e.g. using this after build plugin for webpack). Then you should be able to require the module with an AMD loader.

Original Answer:

require.js loads it's dependencies asynchronously, you have to declare them explicitly when you're not using the r.js optimizer or the like. So if the module exposes an AMD definition it should work like this:

// It works the way you did it ...
define(['path/to/your/module'], function (require, exports, module) {
    require('path/to/your/module'); // -> { ... }
});

// ... but I personally prefer this explicit syntax + it is
// friendlier to a code minifier
define(['path/to/your/module'], function (yourModule) {
    console.log(yourModule); // { ... }
});

Maybe you have to configure your require instance, there are docs for that.

EDIT1: as pointed out the way the module is being accessed is not wrong but the dependencies were missing, so I added code that is closer to the original question.

like image 40
mfeineis Avatar answered Oct 04 '22 04:10

mfeineis