Search code examples
knockout.jsrequirejsknockout-validation

Knockout validation require unknown knockout js file


I am using require js and knockout js to develop coredova app, When I am using knockout validation, it does not work , it says "Script error for: knockout". It displays following in inspect element under Network , www/js/knockout.js 404 Not found, but in js folder there is no knockout.js file, but it require that file, This error comes only when i use knockout.validation in define method.But why it asked this type of knockout js file I made simple code for demostration, please help me

This is my viewModel

define(['knockout-3.2.0','knockout.validation'], function(ko,validation) {

    return function appViewModel() {
        this.firstName = ko.observable('Bert').extend({ number: true,minLength: 3, maxLength: 10 });

    };
});

this is my require path setup

require.config({
    paths: {
        'jQuery': 'jQuery/jquery-2.1.1.min',
        'knockout-3.2.0': 'ko/knockout-3.2.0',
        'knockout.validation': 'ko/knockout.validation'

    },
    shim: {
        'jQuery': {
            exports: '$'
        },
        'knockout-3.2.0': {
            exports: 'ko'
        },
        "knockout.validation": {
             exports: 'validation'
         }
    }

});

Solution

  • Knockout and also the Knockout-Validation plugin support both the CommonJS and the AMD module pattern, so there is no need to shim them.

    You get the error because the Knockout-Validation plugin explicitly depends a module named "knockout" (see on GitHub) so to fix it you need to rename your 'knockout-3.2.0' module to "knockout".

    So the fixed require.js config would look like:

    require.config({
        paths: {
            'jQuery': 'jQuery/jquery-2.1.1.min',
            'knockout': 'ko/knockout-3.2.0',
            'knockout.validation': 'ko/knockout.validation'
    
        },
        shim: {
            'jQuery': {
                exports: '$'
            }
        }
    
    });
    

    And of course in your module you need to use the name "knockout":

    define(['knockout','knockout.validation'], function(ko, validation) {
    
        return function appViewModel() {
            this.firstName = ko.observable('Bert').extend({ number: true,minLength: 3, maxLength: 10 });
    
        };
    });