skip to Main Content

I am learning Javascript and Electron. The app has an entry point named ‘main.js’. I am just getting familiar with making calls to an API, so the scripts at the moment are very basic and don’t have any frontend. Basically, I am logging in, getting some data and logging out. It all works fine when the functions are in main.js, but now I am trying to move one of the functions to a different .js file and, depending on whether I use the import or require keywords and syntax, I get either the ‘Cannot use import statement outside a module’ or the ‘xxx is not a function’ errors. I also tried to change the extension as ‘main.mjs’ (I read this in another post as a possible solution) but it does not work. Obviously, I’m doing something wrong, but I can’t understand what. Would anyone be so kind as to explain?

This is the code for ‘main.js’:

import auth from './auth.js';

// disable the server's self-signed certificate validation
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'

const serviceLayer = 'https://xxx.xxx.xxx.xxx:50000/b1s/v1/'
const data = {
    "CompanyDB": "myDB",
    "UserName": "myUsername",
    "Password": "myPassword"
}

const login = async () => {
    try {
        const url = serviceLayer + 'Login'
        const customHeaders = {
            'Content-Type': "application/json",
        }

        const response = await fetch(url, {
            method: 'POST',
            headers: customHeaders,
            body: JSON.stringify(data),
            credentials: 'include' // include cookies in the request
        })

        const cookiesArray = response.headers.getSetCookie()
        const sessionId = cookiesArray[0].substring(10, 68)
        const node = cookiesArray[1].substring(8, 14)
        const cookies = {
            'B1SESSION': sessionId,
            'ROUTEID': node
        }

        return cookies
    } catch (error) {
        console.log(error);
    }
}

const getOwor = async (session, node, id) => {
    try {
        const url = serviceLayer + 'ProductionOrders(' + id + ')'
        const customHeaders = {
            'Content-Type': "application/json",
            'Cookie': "B1SESSION=" + session + ";ROUTEID=" + node
        }

        const response = await fetch(url, {
            method: 'GET',
            headers: customHeaders
        })

        const json = response.json()
        return json
    } catch (error) {
        console.log(error);
    }
}

(async function () {
    const cookies = await login();
    console.log(cookies)
    const owor = await getOwor(cookies['B1SESSION'], cookies['ROUTEID'], 87);
    console.log(owor)
    const logoutStatus = await auth.logout(cookies['B1SESSION'], cookies['ROUTEID']);
    console.log(logoutStatus)
    process.exit()
})()

This is the code for ‘auth.js’:

const logout = async (session, node) => {
    try {
        const url = serviceLayer + 'Logout'
        const customHeaders = {
            'Content-Type': "application/json",
            'Cookie': "B1SESSION=" + session + ";ROUTEID=" + node
        }

        const response = await fetch(url, {
            method: 'POST',
            headers: customHeaders,
            body: JSON.stringify(data)
        })

        const status = response.status
        return status
    } catch (error) {
        console.log(error);
    }
}

export default logout

And, finally, this is the error:

Uncaught Exception: C:……main.js:1
import auth from ‘./auth.js’;
Syntax error: Cannot use import statement outside a module

3

Answers


  1. if you have an HTML file make sure you defined in <script src="..." type: "module">
    or define it in package.json

    Login or Signup to reply.
  2. Add "type":"module" to your package.json file.

    {
      "type": "module",
    }
    
    

    This should fix the issue.

    Login or Signup to reply.
  3. Please forget what other answers say about "type": "module": this is a Node.js only approach to module resolution and has nothing to do with JavaScript and your question.

    To expose JavaScript modules, just name your modules with the .mjs extensions instead of .js. .mjs is the natively supported extensions for ES modules, and is mandatory for modules that either want to use the import or export syntax.

    Since your main entry point is already a proper ES module (main.mjs), you just need to also make auth a proper ES module by renaming auth.js to auth.mjs.

    And of course import it in main.mjs using its proper extension:

    import auth from './auth.mjs';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search