Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.
This repository was archived by the owner on Dec 12, 2021. It is now read-only.

Not webpack/browserify friendly #12

Closed

Description

@Cellule

I checked the code a bit and realized that the require function is cached, modified and wrapped. Is it really necessary ? Since the actual require is wrapped in a try catch, why not simple use the require function and catch if any error occurs?

see the error below

WARNING in ./~/validate.js/validate.js
Critical dependencies:
456:13-20 require function is used in a way, in which dependencies cannot be statically extracted
 @ ./~/validate.js/validate.js 456:13-20

You can see more info on good practices here https://github.com/umdjs/umd

Activity

  1. ansman commented on Dec 9, 2014

    @ansman
    Owner

    Well, the reason for it was to make it work in both node and browsers but there is perhaps that isn't needed.

    What is the actual problem with this? Why do you need to statically determine the dependencies?

    Also, sorry for not responding earlier. For some reason I didn't get notified as I usually do.

  2. Cellule commented on Dec 11, 2014

    @Cellule
    ContributorAuthor

    I don't have time to properly test, but from I remember it's because you save the require function in a variable then use the require from there. I think that simply removing this assignation and using require directly instead of v.require would solve the problem.
    Right now my only solution is to add to webpack config:

    module: {
      // FIXME:: Webpack must not parse this module because cannot be statically
      // analysed
      noParse: /validate\.js/
    },

    which is a big problem because I can't use moment.js that way (webpack has the responsibility to modify the require("moment") call to an internal call.

  3. Cellule commented on Dec 11, 2014

    @Cellule
    ContributorAuthor

    If you want I can investigate a bit more and make a pull request, however it will have to wait because I am in my finals right now

  4. ansman commented on Dec 11, 2014

    @ansman
    Owner

    I'm guessing that the problem is actually that we pass in a variable as the module name rather than an inlined string so it can't statically determine the module name.

    For for example I had used require('foobar'); it can parse that and figure out that it depends on foobar while if I write var name = 'foobar'; require(name); it can't.

    So the solution would be to switch this:

    var moment = v.tryRequire("moment");

    with this:

    var moment;
    try {
      moment = require("moment");
    } catch(e) {
      moment = null;
    }

    Not sure what consequences this might have.

    If you have time please investigate this further as I'm leaving for vacation tomorrow :)

  5. alexkaraman85 commented on Dec 31, 2014

    @alexkaraman85

    @ansman I ran into the same issue today while using browserify. The dependencies in browserify are determined statically at bundle compile time.

    The issue is exactly what you said, browserify/webpack does not know how to parse require(variable);.

    I don't think the solution is as easy as the code above. Sure, by using the text "moment" webpack and browserify will be able to pick up the dependency, but there are 6 uses of tryRequire in validate.js. You open yourself up to using the text version of require for all of those dependencies, to keep all static bundlers happy.

    Once you start using require('es6-promise'), require('rsvp') browserify is going to bundle in all those requires. Which will grow the bundle size unnecessarily.

    The simplest solution that I can think off is that you don't require dependencies in validate.js at all, but rather make the consumer pass in the required dependencies.

    @Cellule is it possible to rename this issue to also have "browserify" in the title? It took me a while to find this issue since I am not too familiar with webpack.

    I am currently getting around this issue by overriding the 'parse' and 'format' members of 'validate.validators.datetime'.

      validate.validators.datetime.parse = function(value, options) {
        return +moment.utc(value);
      };
    
      validate.validators.datetime.format = function(date, options) {
        format = format || (options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm:ss");
        return moment.utc(date).format(format);
      };
  6. Cellule commented on Jan 2, 2015

    @Cellule
    ContributorAuthor

    I can check into fixing the issue for webpack, unfortunately I have no experience with browserify. I think providing the libraries could be a good solution. I will let you decide on this. I know that for webpack it is not a problem, it will detect and handle correctly if the library is available or not (and warn you).

  7. changed the title [-]Not webpack friendly[/-] [+]Not webpack/browserify friendly[/+] on Jan 2, 2015
  8. ansman commented on Jan 20, 2015

    @ansman
    Owner

    @alexkaraman85 This is a tricky one.
    I would rather not have a setup required before you can use the library.

    I'm guessing the problem stems from the require function only existing in compile time and not runtime, right?

    We could perhaps have support for both, that we first look for moment in the validate object and if that fails we fall back to require, would that work for you?

  9. mosch commented on Jan 28, 2015

    @mosch

    @ansman i think webpack will still fail on trying to solve the "require" call in the code - because it's still there.
    Whats the point in supporting EcmaScript 6 Promises, and three different alternatives? May using traceur-compiler / 6to5 be an alternative?

  10. jhnns commented on Jan 28, 2015

    @jhnns

    A more beautiful solution would be to unify moment's and XDate's API into one and use that instead. This would even clean-up your code.

    Your users would have to overwrite the dateParser to use moment or XDate or whatever they like:

    validate.dateParser = function (dateString) {
        return moment.utc(dateString);
    };

    By default you could use the basic Date object which is also able to parse some date strings:

    validate.dateParser = function (dateString) {
        return new Date(dateString).getTime();
    };

    Thus you would even not depend on any library if your users only need basic parsing capabilities.

    And concerning promises: I'd just use the global Promise object, which will be in all the JS engines soon. Just write in your README that your library requires a polyfill for the Promise object. There are polyfills by all the popular libraries like q or when.

  11. ansman commented on Feb 5, 2015

    @ansman
    Owner

    Well, my concern is that it would be more work for people using node.js

    How about that we hide the fact that we use require from browserify or webpack?
    Something like this:

    var r = root["require"];
    if (!v.isFunction(r)) {
      return null;
    }
    // Regular require code

    This way it would work if you have an AMD loader in your browser and on node but on tools that parse your JS to analyze your deps it would think that we have no dependencies.

  12. alexkaraman85 commented on Feb 12, 2015

    @alexkaraman85

    @ansman

    If you were to hide the requires of validate.js from node.js bundlers then you would lose the Promises and Datetime functionality.

    One other option is that tryRequire goes away and you only use require("text"). This way you code will work for the client and server uses of require. The downfall is that the bundle will be unnecessarily heavy if the consumer does not use Asynch Validation and/or Datetime(double trouble with XDate and Moment).

    To me, the core issue is that validate.js has a possible dependency on optional modules. I mostly agree with @jhnns, if a dependency can be avoided it should be, however, I don't think you should create a new date library by unifying XDate and Moment. Maybe you create a hard dependency on Moment.js and thats it, no more options. Same applies for promises. Still, I think tryRequire needs to go away, it's an interrupter to a standard that can be used in many unpredictable fashions.

  13. ansman commented on Mar 14, 2015

    @ansman
    Owner

    @alexkaraman85 The reason I want to hide the require function is because I only want to run it at runtime, not when the static analyser is trying to figure out the dependency graph.

    Why wouldn't it work to mask the fact that we use require?
    This is the output from node.js

    > this["require"]
    { [Function: require]
      resolve: [Function],
      main: undefined,
      extensions:
       { '.js': [Function],
         '.json': [Function],
         '.node': [Function: dlopen] },
      registerExtension: [Function],
      cache: {} }
    > var validate = this["require"]("./validate.js");
    undefined
    > validate.validate();
    undefined
    

    Browserify exposes the require function at runtime so this should work there. If webpack doesn't do that then the people who use it will just have to manually inject it like people have suggested.

  14. ansman commented on Mar 14, 2015

    @ansman
    Owner

    In fact, I just tried it in Browserify and it works as expected. You'd have to manually include for example moment.js if you wanted that but otherwise it picks it up in runtime.

  15. jhnns commented on Mar 14, 2015

    @jhnns

    this["require"] is only working in node when using the CLI (because this is the global object then). In a module context, this is module.exports which has no require() function.

    But you can write module["require"] and that works in node and webpack (haven't tested browserify though).

  16. ansman commented on Mar 14, 2015

    @ansman
    Owner

    Hmm, this["require"] might only work in the CLI but passing require as a function like we do in validate.js works.

    I tried running the following things:

    $ npm install moment
    [email protected] node_modules/moment
    
    $ cat test.js
    var validate = require("./validate");
    console.log(validate.validators.datetime.parse("2015-03-14"));
    
    $ node test.js
    1426291200000
    
    $ npm uninstall moment
    unbuild [email protected]
    
    $ node test.js
    validate.js:809
            throw new Error("Neither XDate or moment.js was found");
                  ^
    Error: Neither XDate or moment.js was found
        at Function.validate.validators.datetime.v.extend.parse (validate.js:809:15)
        at Object.<anonymous> (test.js:2:42)
        at Module._compile (module.js:460:26)
        at Object.Module._extensions..js (module.js:478:10)
        at Module.load (module.js:355:32)
        at Function.Module._load (module.js:310:12)
        at Function.Module.runMain (module.js:501:10)
        at startup (node.js:129:16)
        at node.js:814:3
    
  17. jhnns commented on Mar 14, 2015

    @jhnns

    It's just that all these trickeries are not necessary imho. Just provide an API where your users can plug-in their favorite date parsing library :)

  18. ansman commented on Mar 14, 2015

    @ansman
    Owner

    I already have. You can simply set validate.Promise to the constructor of the actual promise an override validate.validators.datetime.parse and validate.validators.datetime.format.

    The other stuff is simply convenience methods which is why I would like to suppress the warnings and close this issue.

  19. alexkaraman85 commented on Mar 15, 2015

    @alexkaraman85

    @ansman what is your need for this requirement?
    The reason I want to hide the require function is because I only want to run it at runtime, not when the static analyser is trying to figure out the dependency graph.

    IMHO: For now it makes sense to leave the code as is and add to the documentation the way to provide the dependency on a date lib. At the moment the only way I found to use moment.js with browserify is as mentioned up above.

     validate.validators.datetime.parse = function(value, options) {
        return +moment.utc(value);
      };
    
      validate.validators.datetime.format = function(date, options) {
        format = format || (options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm:ss");
        return moment.utc(date).format(format);
      };
  20. ansman commented on Mar 15, 2015

    @ansman
    Owner

    Here is a working example of how to get moment working with validate.js and browserify:

    $ npm install moment validate.js
    [email protected] node_modules/validate.js
    [email protected] node_modules/moment
    
    $ cat main.js
    var validate = require("validate.js");
    console.log(validate.validators.datetime.parse("2015-03-14"));
    
    $ cat index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title></title>
    </head>
    <body>
      <script src="bundle.js"></script>
    </body>
    </html>
    
    $ browserify -o bundle.js -r moment main.js
    

    Now you can simply open index.html in your favourite browser and open the console to confirm that it works as expected, no warnings.

    As for webpack it does cause a lot of warnings but then you may simply do as @Cellule does and mark it as noParse since webpack doesn't seem to support optional dependencies without throwing a bunch of warnings.

    I will rethink the dependencies before I release 1.0 but until then things will remain like this. I just don't want this library to require a huge setup when using it.

  21. ansman commented on Mar 15, 2015

    @ansman
    Owner

    I started playing around with the idea of having to manually set moment, XDate, RSVP etc and it's not that bad, I admit defeat :)

    Firstly it removes the need for tryRequire and the complex dependency management.
    The code would then look like this:

    var validate = require("validate.js");
    validate.moment = require("moment");
    console.log(validate.validators.datetime.parse("2015-03-14"));

    and when running in a browser we simply use the global moment object.

    I'll make sure to implement this for the next release.

  22. ansman commented on Mar 15, 2015

    @ansman
    Owner

    Released in 0.6.0

  23. jhnns commented on Mar 15, 2015

    @jhnns

    I started playing around with the idea of having to manually set moment, XDate, RSVP etc and it's not that bad, I admit defeat

    👍 for changing opinions 😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions