Sequelize - π index.js β module νμ μΌλ‘ μμ νκΈ°
import μ¬μ©μ μν index.js μμ νκΈ°
require λμ μ import λ¬Έμ μ¬μ©νκΈ° μν΄ package.json
μμ type module μ€μ μ νλλβ¦
sequelize - index.js
μμ μλμ ꡬ문μμ λ¬Έμ κ° λ°μνμ΅λλ€.
//...
fs.readdirSync(__dirname)
.filter((file) => {
console.log(file);
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
// π λ°λ‘ μ¬κΈ° require()λΆλΆ!!!!!
const model = require(path.join(__dirname, file));
console.log(file, model.name);
db[model.name] = model;
model.initiate(sequelize);
});
μλμ κ°μ΄ require
λΆλΆμμ μ€λ₯κ° λ°μνμ΅λλ€.
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/midas/Desktop/Projects/node-js/malcopolo/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
ES Module μμλ require
λ₯Ό μ¬μ©ν μ μλ λΆλΆμ΄μ£ . π€
νμ§λ§ models ν΄λμμ entity κ°μ²΄λ₯Ό μ΄κΈ°ν ν΄μ£ΌκΈ° μν΄μλ νμν ꡬ문μ΄μμ΅λλ€.
λ€νν λ체 κ°λ₯ν μ½λλ₯Ό μ μμ±ν μ¬μ΄νΈλ₯Ό μ°Ύμ μ μμ΄μ μλμ κ°μ΄ μμ±νμ΅λλ€.
// models/index.js
import Sequelize from "sequelize";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import Config from "../config/config.json" assert { type: "json" };
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const env = process.env.NODE_ENV || "development";
const config = Config[env];
const db = {};
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
export default async () => {
const files = fs.readdirSync(__dirname).filter((file) => {
return (
file.indexOf(".") !== 0 &&
file !== path.basename(__filename) &&
file.slice(-3) === ".js"
);
});
for await (const file of files) {
// π μ΄ λΆλΆμ΄ importλ‘ ν΄λΉ νμΌμ κ°μ²΄λ₯Ό μμ±νλ λΆλΆ!
const model = await import(`./${file}`);
model.default.initiate(sequelize);
}
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
return db;
};
model.default.initiate(sequelize);
model.default
λ₯Ό μ¬μ©ν μ΄μ λ ν΄λΉ import λ¬ΈμΌλ‘ λ°μμ¨ model
μ λ‘κ·Έλ‘ μΆλ ₯ ν΄λ³΄λ©΄β¦
μλμ κ°μ΄ default μμ κ°μ΄ λ€μ΄μκΈ° λλ¬Έμ
λλ€.
[Module: null prototype] { default: User }
π₯Έ κ·Έλ¦¬κ³ !! μ¬μ©νλ λΆλΆλ export λΆλΆμ΄ ν¨μλ‘ λ΄λ³΄λ΄κΈ° λλ¬Έμ, μλμ κ°μ΄ μ¬μ©ν μ μμμ΅λλ€.
// app.js
import db from "./models/index.js";
// π μ΄ λΆλΆ!
const database = await db();
const sequelize = database.sequelize;
sequelize
.sync({ force: false })
.then(() => {
console.log("λ°μ΄ν°λ² μ΄μ€ μ°κ²° μ±κ³΅");
})
.catch((err) => {
console.error(err);
});
πΊ κ³ λ‘ λ°μ΄ν° λ² μ΄μ€ μ°κ²° μ±κ³΅!
π μ°Έκ³ μ¬μ΄νΈ