Skip to content

Sequelize + Webpack in 2021 - Can you help me? #13169

Closed

Description

@papb

Hello everyone. Many people have reported problems with Sequelize + Webpack in the last few years. I can guess that the root of the problem is some kind of dynamic require involving the optional dialects supported by Sequelize.

However, I have had a hard time exploring the problem for a few reasons:

  • I never used Webpack
  • Most resources I found on the internet were thinking of Webpack for the frontend (which is probably the most popular usage)
  • The resources I found about Webpack for backend seemed very outdated
  • My quick attempts of reproducing the problem failed
  • I also haven't used things like Serverless, Azure and AWS Lambda (which seem to be mentioned in the same issues) - I don't have enough knowledge to decide whether or not those are just red herrings and all issues stem from the first cause or not.
  • Most issues were opened several years ago and I couldn't be sure if the original problem (mentioned in the first post) still happens or if people are just using the related issue to comment about related (but not-exactly-the-same) problems.
  • My lack of experience/knowledge with bundlers like Webpack does not allow me to evaluate if the problems are Sequelize's fault, Webpack's fault or the users' fault (like a misconfiguration of some kind).

I noticed two main types of issues:

My first guess is that the problem is in this code. Especially since the other place which used to perform dynamic requires in our source code was refactored in 2019 via #11464.

However, I need to really understand the problem in order to fix it, because I want to write a failing test first, and only then fix this. The failing test will probably be a separate workflow for GitHub actions which is going to really install Webpack and run it and see that it works.

Can anyone create a new MCVE for both cases (Type A and Type B) in the form of a public GitHub repository that I can clone and run npm install && npm start to see the problem?

I will then use that as a starting point for the new GitHub workflow that is going to test this.

Activity

  1. papb commented on Apr 4, 2021

    @papb
    MemberAuthor

    By the way, here is my quick (failed) attempt to see the first type of problem happening myself (after following a quick Webpack setup from a tutorial):

    // Entrypoint
    import { Sequelize } from 'sequelize';
    // webpack.config.js
    const fs = require('fs');
    module.exports = {
      // ...
      target: 'node',
      externals: Object.fromEntries(
        fs.readdirSync('node_modules').filter(x => x !== 'bin').map(x => [x, 'commonjs ' + x])
      )
    };
  2. pinned this issue on Apr 4, 2021
  3. papb commented on Apr 4, 2021

    @papb
    MemberAuthor

    After looking at #9608, I am wondering if the dialectModule option solves at least part of these problems?

  4. AwolDes commented on Apr 4, 2021

    @AwolDes

    @papb from what I know & from what I have experienced, you are right when you say:

    the root of the problem is some kind of dynamic require involving the optional dialects supported by Sequelize.

    Webpack is used to bundle javascript, both on the frontend & on the server (especially when using Lambda and similar serverless solutions).

    I fixed both "Type A" and "Type B" errors by using require syntax, and not import syntax for packages, particularly Sequelize (although I think this might come down to my configuration, I'm not 100% sure). My PoC repo https://github.com/AwolDes/express-sequlize-lambda-webpack-poc mentioned in #12874 might be a good place to start to try and re-produce. I wonder if adding the changes in #9609 would help

  5. Trinovantes commented on Apr 5, 2021

    @Trinovantes

    Here's an example for type A using latest Webpack https://github.com/Trinovantes/issue-sequelize-webpack

    As I mentioned this in #7509 (comment), Webpack bundles every dependency into a single file. If it can't know for sure at compile time that something may/may not be needed, it includes it to be safe:

    sequelize/src/data-types.js

    Lines 1023 to 1027 in a8b8b7f

    dialectMap.postgres = require('./dialects/postgres/data-types')(DataTypes);
    dialectMap.mysql = require('./dialects/mysql/data-types')(DataTypes);
    dialectMap.mariadb = require('./dialects/mariadb/data-types')(DataTypes);
    dialectMap.sqlite = require('./dialects/sqlite/data-types')(DataTypes);
    dialectMap.mssql = require('./dialects/mssql/data-types')(DataTypes);

    From Webpack's perspective, all of these requires might be executed at runtime so it'll try to bundle them and fail

  6. Keimeno commented on Apr 5, 2021

    @Keimeno
    Member

    A possible solution might be to dynamically require all dialects:

    const dialects = ['postgres', 'mysql', ...];
    dialects.forEach(dialect => dialectMap[dialect] = require(`./dialects/${dialect}/data-types`)(DataTypes));

    or only require if a given dialect should be used

    // input from developer
    const dialect = 'postgres';
    dialectMap[dialect] = require(`./dialects/${dialect}/data-types`)(DataTypes);

    But this could potentially still cause problems with webpack, as the dialects might not be included at all in that case.

  7. Trinovantes commented on Apr 6, 2021

    @Trinovantes

    I think a plugin system would work:

    import { Sequelize } from 'sequlize'
    import MysqlDialect from 'sequelize/plugins/mysql'
    Sequelize.use(MysqlDialect)

    This is similar to how other libraries like dayjs handle optional components and compatibility with webpack https://day.js.org/docs/en/plugin/relative-time

  8. HirenPatel2791 commented on Apr 12, 2021

    @HirenPatel2791

    This worked for me for serverless-bundle.

    "serverless": "^2.10.0",
    "node": "12.x"
    "serverless-bundle": "^3.2.1"
    "sequelize": "^6.6.2"
    

    serverless.yml (this solves: 'Module not found: Error: Can't resolve 'pg-hstore' in '/Users/.../node_modules/sequelize/lib/dialects/postgres')

    custom:
      bundle:
          ignorePackages: 
            - pg-hstore
    

    Now since it's ignoring the pg dialect module, I need to define my dialect module like when init sequelize.

    const { Sequelize } = require('sequelize');
    const mysql = require('mysql2');
    
    const sequelize = new Sequelize(
        process.env.DB_NAME || 'blah',
        process.env.DB_USER || 'blah',
        process.env.DB_PASS || 'blah',
        {
            host: process.env.DB_URL || 'localhost',
            dialect: 'mysql',
            dialectModule: mysql
        }
    );
    
    export default sequelize;
    
  9. invaderb commented on Jun 3, 2021

    @invaderb

    I was able to get sequelize working with serverless-bundle with @HirenPatel2791 recommendation, but not with just serverless-webpack.

    serverless bundle doesn't leave much for configuration and no minification so the files are much larger.

    @papb with serverless-webpack I tried the dialectModule and was still getting errors and warnings.

  10. github-actions commented on Oct 27, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  11. github-actions commented on Nov 5, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  12. 6 remaining items

  13. ephys commented on Jan 18, 2023

    @ephys
    Member

    You need to install pg-hstore if you want to bundle sequelize instead of loading it as an external

    In Sequelize 6, pg-hstore is an optional dependency that you must install if you use DataTypes.HSTORE. It's loaded dynamically

    Rollup can't do that so it tries to bundle it, so you need to either make it an external or install it

    In Sequelize 7, pg-hstore is always installed because it's a tiny library and we're going to move each dialect to its own package (e.g. @sequelize/postgres) which should resolve this problem. (#15553)

    The dialect split should also resolve the remaining bundling issues as we will not be loading dependencies dynamically anymore

  14. bhallstein commented on Jan 19, 2023

    @bhallstein

    Thanks very much for the informative reply @ephys! Simply installing pg-hstore does seem to resolve the missing dependency issue, and as you say, it's not a large dependency.

    I looked further into handling dynamic require rollup-side, and in fact the commonjs plugin has config to allow this — this is the config that I'm currently testing (currently partly blocked on this due to another tooling issue, will update this comment when able to test fully):

    commonjs({
      include: /node_modules/,
      dynamicRequireTargets: [
        '**/node_modules/sequelize/**/*.js',
      ],
      dynamicRequireRoot: `node_modules`,
      transformMixedEsModules: true,
    }),

    The dialect split sounds like a good resolution for the future.

    Thanks again for your help.

  15. Zenlight commented on Jan 22, 2023

    @Zenlight

    Hello all! I happen to just receive the same error as above in addition to one more. The first one went away when I installed pg-hstore.
    However, now I'm left with this error:

    vue    |  ERROR  Failed to compile with 1 error6:14:41 PM
    vue    | 
    vue    | This dependency was not found:
    vue    | 
    vue    | * node:util in /node_modules/sequelize/lib/dialects/db2/query.js
    vue    | 
    vue    | To install it, you can run: npm install --save node:util
    vue    | <s> [webpack.Progress] 100% 
    

    Ive tried the externals and plugins fix, but I'm still receiving the error above.
    Any help is appreciated, thank you!

  16. bhallstein commented on Jan 22, 2023

    @bhallstein

    @Zenlight Vue builds for the browser, where node’s library functions aren’t available – see #6424

    You might be able to shim the node library using browserify, but you’re likely to be better off using a library built for the browser. Maybe have a look at knex?

  17. Zenlight commented on Jan 22, 2023

    @Zenlight

    Hi @bhallstein. I will look into that tomorrow and get back you. Thanks for the quick response!

  18. xlinxie commented on May 13, 2023

    @xlinxie

    After looking at #9608, I am wondering if the dialectModule option solves at least part of these problems?

    dialectModule solves the Please install {some-package} manually problem

  19. sallyzoughaib commented on Dec 1, 2023

    @sallyzoughaib

    @bhallstein I am minifying and bundling a Node.js TypeScript backend project that uses Sequelize to connect with a database. I used Webpack for this task and successfully generated the 'bundle.js' file. However, when I ran 'node dist/bundle.js,' the server started, but any request requiring a database connection resulted in an error. After debugging and investigating, I discovered that I am missing Sequelize configurations in my 'web.config.js' file. Could you please help me identify what's missing?
    this is my webpack.config.js:

    var path = require('path');
    var fs = require('fs');
    var nodeModules = {};
    fs.readdirSync('node_modules')
      .filter(function (x) {
        return ['.bin'].indexOf(x) === -1;
      })
      .forEach(function (mod) {
        nodeModules[mod] = 'commonjs ' + mod;
      });
    
    module.exports = {
      mode: 'development',
      target: 'node',
      entry: './src/server.ts',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      resolve: {
        extensions: ['.ts', '.js'],
        alias: {
          '@': path.resolve(__dirname, 'src'),
          '@config': path.resolve(__dirname, 'src/config'),
          '@controllers': path.resolve(__dirname, 'src/controllers'),
          '@dtos': path.resolve(__dirname, 'src/dtos'),
          '@exceptions': path.resolve(__dirname, 'src/exceptions'),
          '@interfaces': path.resolve(__dirname, 'src/interfaces'),
          '@middlewares': path.resolve(__dirname, 'src/middlewares'),
          '@models': path.resolve(__dirname, 'src/models'),
          '@routes': path.resolve(__dirname, 'src/routes'),
          '@services': path.resolve(__dirname, 'src/services'),
          '@utils': path.resolve(__dirname, 'src/utils'),
          '@sentry/profiling-node': path.resolve(__dirname, 'node_modules/@sentry/profiling-node'),
        },
      },
      module: {
        rules: [
          {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/,
          },
          {
            test: /\.node$/,
            loader: 'node-loader',
          },
        ],
      },
      externals: [nodeModules],
      devtool: 'source-map',
    };
    
  20. bhallstein commented on Dec 3, 2023

    @bhallstein

    @sallyzoughaib Happy to try to help but I don't want to spam this issue (to be clear I'm not affiliated with Sequelize). If you have a Discord account feel free to repost the question in #help-programming on https://discord.gg/C2JpWRcG

  21. sallyzoughaib commented on Dec 4, 2023

    @sallyzoughaib

    @bhallstein thank you,
    Now I am attempting using Rollup to bundle my Node.js TypeScript backend application code and dependencies (node_modules) into a single JavaScript file named "bundle.js".

    I got this error when i ran npm run build

    where build : rollup -c

    Error: [!] (plugin rpt2) Error: Unexpected character '�' (Note that you need plugins to import files that are not JavaScript)node_modules/@sentry/profiling-node/lib/sentry_cpu_profiler-darwin-x64-93.node (1:0)

    This is my rollup.config.js filer:

    import alias from '@rollup/plugin-alias';
    import nodeBuiltins from 'rollup-plugin-node-builtins';
    import commonjs from 'rollup-plugin-commonjs';
    import resolve from 'rollup-plugin-node-resolve';
    import typescript from 'rollup-plugin-typescript2';
    import tslibResolveId from 'rollup-plugin-tslib-resolve-id';
    import json from '@rollup/plugin-json';

    export default {
    input: 'src/server.ts',
    output: {
    file: 'dist/bundle.js',
    format: 'es',
    },
    plugins: [
    nodeBuiltins(),
    tslibResolveId(),
    typescript(),
    json(),
    commonjs({
    include: 'node_modules/**',
    ignoreGlobal: false,
    sourceMap: false,
    }),
    alias({
    entries: [
    { find: '@config', replacement: 'config' },
    { find: '@controllers', replacement: 'controllers' },
    { find: '@middlewares', replacement: 'middlewares' },
    { find: '@routes', replacement: 'routes' },
    { find: '@services', replacement: 'services' },
    ],
    }),
    resolve(),
    ],
    };

  22. anotherCoward commented on Apr 3, 2024

    @anotherCoward

    I was having a similar issues with nextjs (14.1.4), sequelize (6.37.1) and mysql2 (3.9.3).

    It was running fine under dev but when I tried build it failed because mysql2 gets require()'d inside a constructor function and this seems to be ignored by webpack, when generating the bundles.

    Without the prop dialectModule, I always got the MODULE_NOT_FOUND Error. So it was kinda mandatory to implement it there.

    import Sequelize from "sequelize";
    // generated by sequelize-auto
    import initModels from "./init-models";
    import mysql2 from "mysql2";
    
    const {
        MARIADB_SERVER,
        MARIADB_USER,
        MARIADB_PASS,
        MARIADB_DATABASE,
        MARIADB_PORT,
        MARIADB_CHARSET,
      } = process.env,
      options = {
        dialect: "mysql",
        dialectModule: mysql2,
        logging: process.env.NODE_ENV === "production" ? false : console.log,
        dialectOptions: {
          host: MARIADB_SERVER,
          user: MARIADB_USER,
          password: MARIADB_PASS,
          port: MARIADB_PORT || 3306,
          database: MARIADB_DATABASE,
          multipleStatements: true,
          charset: MARIADB_CHARSET,
        },
      };
    
    const instance = new Sequelize(options);
    
    export default initModels(instance);
    export { instance };

    By using the property dialectModule in the database instanciate script it raised an Error without any matching error message during build. The child process is just stopped with code: 3221225725 (0xc00000fd) which refers to endless recursion.

    PS C:\Dev\test-app> npm run build
    
    > [email protected] build
    > next build
    
       ▲ Next.js 14.1.4
       - Environments: .env
    
       Creating an optimized production build ...
    Compiler server unexpectedly exited with code: 3221225725 and signal: null
    
    > Build error occurred
    Error: Jest worker encountered 1 child process exceptions, exceeding retry limit
        at ChildProcessWorker.initialize (C:\Dev\test-app\node_modules\next\dist\compiled\jest-worker\index.js:708:23)
        at ChildProcessWorker._onExit (C:\Dev\test-app\node_modules\next\dist\compiled\jest-worker\index.js:764:18)   
        at ChildProcess.emit (node:events:526:35)
        at ChildProcess._handle.onexit (node:internal/child_process:291:12) {
      type: 'WorkerError'
    }
    

    I was able to solve the issue by altering the webpack config from within the next.config, which just adds "mysql2" to config.externals.

    const nextConfig = {
    // ...
      webpack(config) {
        if (Array.isArray(config?.externals)) {
          config.externals.push("mysql2");
        } else {
          config.externals = ["mysql2"];
        }
        return config;
      },
    };
    
    export default nextConfig;

    The main cause for the issue are the dialects\[database] scripts and how the drivers are loaded there.

    webpack is unable to find the node module when _loadDialectModule(modulename) is called from the abstract ConnectionManager class after webpack bundled it.

    The best solution would be to alter the connection-manager.js files slightly, as this abstract require()-usage is causing the problem. Webpack also logs Critical dependency: the request of a dependency is an expression when require() is used that way and always refers to the connection-manager-files from the driver/dialect used.

    See also vercel/next.js#50587

  23. ephys commented on Apr 3, 2024

    @ephys
    Member

    All dynamic requires are being phased out in Sequelize 7. _loadDialectModule has already been fully removed. These changes are not released yet and are tracked in #13722

    This should make Sequelize itself bundable, but I can't speak for the libraries we use that handle connecting to the database

  24. anotherCoward commented on Apr 3, 2024

    @anotherCoward

    @ephys that's good news, but there are still tons of projects using older versions, so please keep that in mind too. Some might also require bundling Sequelize 6 (or older) in the package.json.

    It would be easily possible to avoid the module not found error if the connection-manager.js files were slightly altered.

    Example:

    From the current sequelize\lib\mysql\connection-manager.js (6.37.2):

    const { promisify } = require("util");
    class ConnectionManager extends AbstractConnectionManager {
      constructor(dialect, sequelize) {
        sequelize.config.port = sequelize.config.port || 3306;
        super(dialect, sequelize);
        this.lib = this._loadDialectModule("mysql2");

    to:

    const { promisify } = require("util");
    const mysql2 = require("mysql2");
    class ConnectionManager extends AbstractConnectionManager {
      constructor(dialect, sequelize) {
        sequelize.config.port = sequelize.config.port || 3306;
        super(dialect, sequelize);
        this.lib = sequelize.config.dialectModule || mysql2;
        if (typeof sequelize.config.dialectModuleName == "string" && !sequelize.config.dialectModule) {
          this.lib = this._loadDialectModule(sequelize.config.dialectModuleName);
        }

    Also, an upgrade to a new major version might present other challenges, such as rewriting several parts of the project if a method usage was altered.

    I've simply added my research and results for others who are facing these issues. I couldn't find any other solution for the issue that works properly with Next.js 14.1 built-in webpack bundler.

    Thanks for your time.

  25. ephys commented on Apr 3, 2024

    @ephys
    Member

    Unfortunately that is not a change we can implement as it would require all users to install mysql2, instead of just the users that are using the mysql dialect

    If you use dialectModule, try setting it the result of import * as mysql2 from "mysql2"; instead of import mysql2 from "mysql2";

  26. anotherCoward commented on Apr 3, 2024

    @anotherCoward

    @ephys yeah, tough challenge you are facing there. 😅

    Just a suggestion then. It would be nice to see this informations in the documentation under Environment specific things. (also for v6)

    image

    It really took a while to find the cause of the issue, especially when the Jest worker-error showed up without any kind of debugging details.

    npm run dev

    It is recommended to provide the dialectModule-prop to the Sequelize constructor in a Next.js environment to bundle it properly.

    npm run build

    It is also required to add the drivers used, in webpacks config.externals-list, as mentioned here.

    This applies to every usage of webpack together with sequelize to make sure, the dynamic require-calls will work.

    The mentioned solution

    const nextConfig = {
      experimental: {
        serverComponentsExternalPackages: ["sequelize", 'mysql2'],
      },
    }

    isn't really recommended as the experimental feature might change or could be removed at any time.

  27. cirosantilli commented on Jul 27, 2024

    @cirosantilli

    The following is a minimal example of "Please install {some-package} manually". If you replace sequelize with webpack compatible package like lodash it works.

    Adding:

        "pg-hstore": "^2.3.4",
    

    as a workaround to another issue even though it should not be needed in this sqlite example.

    webpack.config.js

    const { ProvidePlugin } = require("webpack")
    
    module.exports = {
      entry: {
        index: ['./index.js'],
      },
      mode: 'none',
      output: {
        filename: '[name].js',
      },
      target: 'node',
    
      // Blows up differently.
      //externals: {
      //  sequelize: 'sequelize',
      //},
    
      // Did not help.
      //plugins: [
      //  new ProvidePlugin({
      //    sqlite3: 'sqlite3',
      //  })
      //]
    }
    

    package.json

    {
      "name": "webpack-cheat",
      "engines": {
        "node": ">=v20.10.0"
      },
      "version": "1.0.0",
      "private": true,
      "scripts": {
        "build": "webpack"
      },
      "author": "Ciro Santilli",
      "license": "MIT",
      "devDependencies": {
        "webpack": "5.93.0",
        "webpack-cli": "5.1.4",
        "webpack-dev-server": "5.0.4"
      },
      "dependencies": {
        "pg-hstore": "^2.3.4",
        "sequelize": "6.14.0",
        "sqlite3": "5.0.2"
      }
    }
    

    index.js

    const assert = require('assert')
    const path = require('path')
    
    /*
    Might move things forward, but fails instead with an error that likely comes from sqlite3
    also not being compatible with webpack:
    
    ERROR in ./node_modules/node-pre-gyp/lib/info.js 14:14-32
    Module not found: Error: Can't resolve 'aws-sdk' in '/home/ciro/bak/git/cirosantilli.github.io/webpack/sequelize/node_modules/node-pre-gyp/lib'
     @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./info.js ./info
     @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
     @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
     @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
     @ ./index.js 3:16-34
    */
    //const sqlite3 = require('sqlite3')
    const { DataTypes, Sequelize } = require('sequelize')
    let sequelize
    if (process.argv[2] === 'p') {
      sequelize = new Sequelize('tmp', undefined, undefined, {
        dialect: 'postgres',
        host: '/var/run/postgresql',
      })
    } else {
      sequelize = new Sequelize({
        dialect: 'sqlite',
        storage: 'tmp.sqlite',
      })
    }
    function assertEqual(rows, rowsExpect) {
      assert.strictEqual(rows.length, rowsExpect.length)
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i]
        let rowExpect = rowsExpect[i]
        for (let key in rowExpect) {
          assert.strictEqual(row[key], rowExpect[key])
        }
      }
    }
    ;(async () => {
    const IntegerNames = sequelize.define('IntegerNames', {
      value: { type: DataTypes.INTEGER },
      name: { type: DataTypes.STRING },
    });
    await IntegerNames.sync({ force: true })
    async function reset() {
      await sequelize.truncate({ cascade: true })
      await IntegerNames.create({ value: 2, name: 'two' })
      await IntegerNames.create({ value: 3, name: 'three' })
      await IntegerNames.create({ value: 5, name: 'five' })
    }
    await reset()
    let rows
    rows = await IntegerNames.findAll({ order: [['value', 'ASC']] })
    assertEqual(rows, [
      { id: 1, value: 2, name: 'two',   },
      { id: 2, value: 3, name: 'three', },
      { id: 3, value: 5, name: 'five',  },
    ])
    })().finally(() => { return sequelize.close() })
    

    run

    npm install
    npx webpack
    node dist/index.js
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: other

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions