Skip to content
Advertisement

cannot use import statement outside a module error

So I have a file and it contains a function

const registerUsernameValidation = (username, n_patt) => {
    if (username.val() == "" || username.val().length > 12 || username.val().length < 3) {
        username.addClass("border-danger");
        $("#u_error").html("<span class='text-danger'>Please Enter A Username</span>");
        status = false;
    } else if (username.val().length > 12) {
        username.addClass("border-danger");
        $("#u_error").html("Please Enter A Username With A Length Less Than 12");
        status = false;
    } else if (username.val().length < 3) {
        username.addClass("border-danger");
        $("#u_error").html("Please Enter A Username With A Length Greater Than 3");
        status = false;
    } else if (!n_patt.test(username.val())) {
        username.addClass("border-danger");
        $("#u_error").html("Please Enter A Valid Username, Only Letters And Numbers");
        status = false;
    } else {
        username.removeClass("border-danger");
        $("#u_error").html("");
        status = true;
    }
}

export {registerUsernameValidation};

my main.js:

import { registerUsernameValidation } from "./validation.js";

$(document).ready(function() {
    $("#register_form").on("submit", function() {
        var username = $("#username");
        var email = $("#email");
        var pass1 = $("#password1");
        var pass2 = $("#password2");
        var type = $("#usertype");
        var n_patt = new RegExp(/^(?![0-9]*$)[a-zA-Z0-9]+$/);
        var e_patt = new RegExp(/^[a-z0-9_-]+(.[a-z0-9_-]+)*@[a-z0-9_-]+(.[a-z0-9_-]+)*(.[a-z]{2,4})$/);
        
        registerUsernameValidation(username, n_patt);
    });
});

and for some reason I still get an error Uncaught SyntaxError: Cannot use import statement outside a module

Advertisement

Answer

Using in Node.js

Add "type": "module" to your package.json. This will tell node that import will be used to import files instead of require.

Using in browser

Add a type="module" attribute to your <script> tag.

Advertisement