How to resolve path to migrations folder after webpack bundling

1.4k Views Asked by At

I need to pass to Umzug config a path to migrations folder but it is being compressed by webpack is it possible to do?

I've tried to bundle each migrations file separately but Umzug saying that it cannot find method up().

    let umzug = new Umzug({
      storage: 'sequelize',

      storageOptions: {
        sequelize: sequelize
      },

      migrations: {
        params: [
          sequelize.getQueryInterface(),
          Sequelize
        ],
        path: './../db/migrations/*')
      }
    })

When I try to run them manually just compiled from the webpack it is saying that no method up().

1

There are 1 best solutions below

2
On BEST ANSWER

I may be a little late to the party since you asked this 7 months ago but I just encountered the same problem so figured I'd post my solution.

I solved this by creating an entrypoint in Webpack for each migration. I used glob to fetch the files dynamically then appended them to the entrypoint parameter, using the filename as the entrypoint name.

Then in the output.filename function, I check for any entrypoints from my previous list. These entrypoint files are then created within a migrations directory to keep them cleanly placed out of the way of the rest of my entrypoint files so that your migrator doesn't try to iterate over them as well.

webpack.config.js

const migrationFiles = glob.sync('./src/migrations/*');
const migrationEntries = migrationFiles.reduce((acc, migrationFile) => {
    const entryName = migrationFile.substring(
        migrationFile.lastIndexOf('/') + 1,
        migrationFile.lastIndexOf('.')
    );
    acc[entryName] = migrationFile;
    return acc;
}, {});

modules.exports {
    entry: {
        index: './src/index.ts',
        ...migrationEntries,
    },

    ...

    output: {
        libraryTarget: 'commonjs',
        filename: chunkData => {
            if (Object.keys(migrationEntries).includes(chunkData.chunk.id)) {
                return `migrations/${chunkData.chunk.id}.js`;
            }

            return '[name].js';
        },
    },
}

Now all of your migrations should be accessible directly as a .js file in your /dist/migrations directory.

Now for loading Umzug, you can just specify the migration directory path

let umzug = new Umzug({
    storage: 'sequelize',

    storageOptions: {
        sequelize: sequelize
    },

    migrations: {
        params: [
            sequelize.getQueryInterface(),
            Sequelize
        ],
        path: path.join(__dirname, 'migrations')
    }
})

I'm sure there's a better solution out there, but this one took me longer than I'd like to admit and solves all of my problems, so that's where I ended my search. Hope this helps someone.