NodeJS 语法错误:无法在模块错误之外使用导入语句

vnzz0bqm  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(217)

我尝试创建续写迁移与打字方法。当我尝试运行npx sequelize-configdb:migrate时,我收到了导入方法错误的错误。我也尝试了一些方法,但我找不到它。
我的文件结构
|Dist| src||config| database.ts |连接|connection.ts |控制器|user.controller.ts |迁移|20231015073945-create-role.ts |模型|index.ts |role.ts |航线|role.router.ts |seeders.ts |20231015075720-role-data.ts ||server.ts |. sequelizer| package.json

database.ts//
require('dotenv').config();

//DB Declare;
module.exports = {
  "development": {
    "username": process.env.DEV_DB_USERNAME,
    "password": process.env.DEV_DB_PASSWORD,
    "database": process.env.DEV_DB_NAME,
    "host": process.env.DEV_DB_HOST,
    "dialect": process.env.DEV_DB_DATABASE_TYPE,
  },
  "test": {
    "username": process.env.TEST_DB_USERNAME,
    "password": process.env.TEST_DB_PASSWORD,
    "database": process.env.TEST_DB_NAME,
    "host": process.env.TEST_DB_HOST,
    "dialect": "mysql"
  },
  "production": {
    "username": process.env.PROD_DB_USERNAME,
    "password": process.env.PROD_DB_PASSWORD,
    "database": process.env.PROD_DB_NAME,
    "host": process.env.PROD_DB_HOST,
    "dialect": "mysql"
  }
};


connection.ts//
//Required;
import { Sequelize } from 'sequelize';

//Declare;
let env;

if (process.env.NODE_ENV === 'test') {
    env = 'test';
} else if (process.env.NODE_ENV === 'production') {
    env = 'production';
} else {
    env = 'development';
}
const config = require('../config/database.ts')[env];

const sequelize = new Sequelize(config.database, config.username, config.password, config);

//Conformation;
(async () => {
    try {
        await sequelize.authenticate();
        console.log('Database connection has been established successfully.');
    } catch (err) {
        console.error('Unable to connect to the database:', (err as Error).message);
    }
})();

module.exports = sequelize;


20231015073945-create-role.ts //migration
'use strict';
import { QueryInterface, DataTypes } from 'sequelize';

module.exports = {
  async up(queryInterface: QueryInterface) {
    await queryInterface.createTable('roles', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      role: {
        allowNull: false,
        type: DataTypes.STRING
      },
      isActive: {
        type: DataTypes.BOOLEAN,
        defaultValue: true
      },
      createdAt: {
        allowNull: true,
        type: DataTypes.DATE
      },
      updatedAt: {
        allowNull: true,
        type: DataTypes.DATE
      }
    });
  },
  async down(queryInterface: QueryInterface) {
    await queryInterface.dropTable('roles');
  }
};

index.ts //models
import fs from 'fs';
import path from 'path';
import { Sequelize, DataTypes } from 'sequelize';
import process from 'process';

const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/database.ts')[env];
const db: any = {};

let sequelize: Sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable] as string, config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter((file: string) => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.ts' &&
      file.indexOf('.test.ts') === -1
    );
  })
  .forEach((file: string) => {
    const model = require(path.join(__dirname, file))(sequelize, DataTypes);
    db[model.name] = model;`your text`
  });

Object.keys(db).forEach((modelName: string) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;

role.ts //models
'use strict';
import { Model, DataTypes, Sequelize } from 'sequelize';

interface RoleAttributes {
  id: number;
  role: string;
  isActive: boolean;
}

module.exports = (sequelize: Sequelize) => {
  class Role extends Model<RoleAttributes> {
    static associate() {
      // Define associations here
    }
  }

  Role.init({
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    role: DataTypes.STRING,
    isActive: DataTypes.BOOLEAN,
  }, {
    sequelize,
    modelName: 'role',
  });

  return Role;
};



server.ts ///////
//Required;
import express from 'express';
const app = express();
import dotenv from 'dotenv';
dotenv.config();
require('./src/connection/connection');

//Declare
const port = process.env.PORT





//Server Listen;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});



.sequelizerc
const path = require('path');

module.exports = {
    'config': path.resolve('src', 'config', 'database.ts'),
    'migrations-path': path.resolve('src', 'migrations'),
    'models-path': path.resolve('src', 'models'),
    'seeders-path': path.resolve('src', 'seeders'),
};



package.json
i am try to add and remove "type: model" method
{
  "name": "server",
  "version": "1.0.0",
  "main": "server.ts",
  "author": "raghul",
  "license": "MIT",
  "private": true,
  "scripts": {
    "start": "nodemon server.ts",
    "dev": "nodemon server.ts",
    "test": "",
    "build": "tsc",
    "prestart": "yarn run build"
  },
  "dependencies": {
    "body-parser": "^1.20.2",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "init": "^0.1.2",
    "mysql2": "^3.6.1",
    "sequelize": "^6.33.0",
    "sequelize-cli": "6.3.0",
    "ts-node": "^10.9.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.19",
    "@types/node": "^20.8.6",
    "tsconfig.json": "^1.0.11",
    "typescript": "^5.2.2"
  }
}
{
  "name": "server",
  "version": "1.0.0",
  "main": "server.ts",
  "author": "raghul",
  "license": "MIT",
  "private": true,
  "scripts": {
    "start": "nodemon server.ts",
    "dev": "nodemon server.ts",
    "test": "",
    "build": "tsc",
    "prestart": "yarn run build"
  },
  "dependencies": {
    "body-parser": "^1.20.2",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "init": "^0.1.2",
    "mysql2": "^3.6.1",
    "sequelize": "^6.33.0",
    "sequelize-cli": "6.3.0",
    "ts-node": "^10.9.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.19",
    "@types/node": "^20.8.6",
    "tsconfig.json": "^1.0.11",
    "typescript": "^5.2.2"
  }
}



tsconfig.json
{
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "target": "es2017",
    "module": "ESNext",------------------------> already tryed commonjs also 
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "./src",
    "paths": {
      "@/*": [
        "*"
      ]
    }
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/**/*.ts",
    "server.ts",
  ]
}```
mfpqipee

mfpqipee1#

typescript使用JavaScript模块,但您使用的是comonjs类型的导出,您必须将导出更改为javascript模块类型或在您的typescript配置文件中设置为支持commonjs
JavaScript模块导出类似于

import dotenv from "dotenv";
dotenv.config()

const config={
  "development": {
    "username": process.env.DEV_DB_USERNAME,
    "password": process.env.DEV_DB_PASSWORD,
    "database": process.env.DEV_DB_NAME,
    "host": process.env.DEV_DB_HOST,
    "dialect": process.env.DEV_DB_DATABASE_TYPE,
  },
  "test": {
    "username": process.env.TEST_DB_USERNAME,
    "password": process.env.TEST_DB_PASSWORD,
    "database": process.env.TEST_DB_NAME,
    "host": process.env.TEST_DB_HOST,
    "dialect": "mysql"
  },
  "production": {
    "username": process.env.PROD_DB_USERNAME,
    "password": process.env.PROD_DB_PASSWORD,
    "database": process.env.PROD_DB_NAME,
    "host": process.env.PROD_DB_HOST,
    "dialect": "mysql"
  }
};

export default config;

或者你可以这样做:

import dotenv from "dotenv";
dotenv.config()

export const config={
  "development": {
    "username": process.env.DEV_DB_USERNAME,
    "password": process.env.DEV_DB_PASSWORD,
    "database": process.env.DEV_DB_NAME,
    "host": process.env.DEV_DB_HOST,
    "dialect": process.env.DEV_DB_DATABASE_TYPE,
  },
  "test": {
    "username": process.env.TEST_DB_USERNAME,
    "password": process.env.TEST_DB_PASSWORD,
    "database": process.env.TEST_DB_NAME,
    "host": process.env.TEST_DB_HOST,
    "dialect": "mysql"
  },
  "production": {
    "username": process.env.PROD_DB_USERNAME,
    "password": process.env.PROD_DB_PASSWORD,
    "database": process.env.PROD_DB_NAME,
    "host": process.env.PROD_DB_HOST,
    "dialect": "mysql"
  }
};

相关问题