简体   繁体   中英

How do I 'require' requirejs in a web js file?

I'm unsure how to implement requirejs in my code. I'm new to web development and HTML (I'm pretty good in JS)

You can't just natively use require(), so I have to use requirejs , but I'm unsure how to get it into my code. It's not like you can just do require('requirejs') . I've looked this up and haven't found an answer that works for me.

This is where I'm using requires:

function getDB(type,id){
    console.log(type,id)
    if (type === 'guild'){
        const guildData = require('./models/guilds.js')
        return guildData.findById(id);
    }
    else if (type === 'eco'){
        const ecoData = require('./models/economy.js')
        return ecoData.findById(id);
    }
    else if (type === 'staff'){
        const staffData = require('./models/staff.js')
        return staffData.findById(id);
    }
    else if (type === 'muted'){
        const mutedData = require('./models/muted.js')
        return mutedData.findById(id);
    }
}

Help me out here!

Hi you need to download it and then you can add it as a script in HTML Code

<head>
   <title>My Sample Project</title>
   <script data-main="scripts/main" src="scripts/require.js"></script>
</head>

require from NodeJS is using CommonJS module format, but require from RequireJS is using AMD module format. They are non compatible.

Just adding RequireJS to your code will not make it work. You have to amend your code.

require from RequireJS does not return a required module. You have to pass the function which will have the module injected to it. Quick fix for you code:

require(['./models/guilds', './models/economy.js', './models/staff.js', './models/muted.js',], (guildData, ecoData, staffData, mutedData) => {
    function getDB(type,id){
        console.log(type,id)
        if (type === 'guild'){
            return guildData.findById(id);
        }
        else if (type === 'eco'){
            return ecoData.findById(id);
        }
        else if (type === 'staff'){
            return staffData.findById(id);
        }
        else if (type === 'muted'){
            return mutedData.findById(id);
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM