-1

How can we import users schema modal in server.js file in ES6 way. Even though I have added type: module in package.json file it doesn't work, throws below error.

note: I am trying to import all of the other modules in ES6 way.

sequelize user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
    const users = sequelize.define('users', {
        id: {
            type: DataTypes.INTEGER(10),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        email: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        password: {
            type: DataTypes.STRING(100),
            allowNull: false
        }
    }, {
        timestamps: true,
        tableName: 'users'
    });

    return users;
};

and in the server.js

import usersSchema from "./modals/users.js";

Throws below error in console:

node:40244)

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Project\study\matblogs\src\server.js:23
soccerway
  • 10,371
  • 19
  • 67
  • 132
  • 2
    Does this answer your question? [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Klea Mar 22 '23 at 06:28

2 Answers2

4

Try using

export default = (sequelize, DataTypes) => {
  ...

Refer to this ES6 101 article which will help you adjust your code: ES6 In Depth: Modules

If you’d like your own ES6 module to have a default export, that’s easy to do. There’s nothing magic about a default export; it’s just like any other export, except it’s named "default". You can use the renaming syntax we already talked about:

```js
let myObject = {
  field1: value1,
  field2: value2
};
export {myObject as default};
```

Or better yet, use this shorthand:

export default {
  field1: value1,
  field2: value2
};
A.Pearsson
  • 61
  • 3
0

The error message indicates that the server.js file is not being recognized as an ES module. To fix this issue, you need to add "type": "module" in your package.json file.

  • Thank you, I did tried that earlier ..at that time I was getting error ... `import usersSchema from "./modals/users.js"; ^^^^^^^^^^^ SyntaxError: The requested module './modals/users.js' does not provide an export named` 'default' – soccerway Mar 21 '23 at 04:54