How to import "path.join" in module?

Viewed 47

I experiencing a problem below. All I know, it's because I added the "type": "module" in my package.json file. But do we have a way to convert the following code in module? I cannot find good resources so far.

const model = require(path.join(__dirname, file))( ReferenceError: require is not defined


My code:

const model = require(path.join(__dirname, file))(
      sequelize,
      Sequelize.DataTypes
    );
    db[model.name] = model;
2 Answers

You replicate this by using dynamic imports. Here's an example using your code:

import(path.join(__dirname, file))
    .then(mod => {
        const model = mod(sequelize, Sequelize.DataTypes);
        db[model.name] = model;
    });

Note that this is run asynchronously. If you're using a most recent version of Node.js that supports top level awaits or this code is being run inside an async function, then you can use this code insteadd:

const mod = await import(path.join(__dirname, file));
const model = mod(sequelize, Sequelize.DataTypes);
db[model.name] = model;

You are calling a function called require and you receive an error which tells you that it's undefined. This is a good indication that your require function is indeed undefined.

It is quite possible that you wanted to use RequireJS: https://requirejs.org/

You will need to make sure that RequireJS is already loaded and properly initialized by the time you try to call require.

If you are using NodeJS, you need to install RequireJS,like

npm install requirejs

If you are trying to use it in your browser, then you will need to link it via a script tag. Here's a tutorial for more information and practical examples: https://www.tutorialspoint.com/requirejs/index.htm

Related