Issue
When building the application with Webpack into a single bundle, the library migrate-mongo
is unable to find the migration schema module eg migrations/[some-number]-[some-name]-migration.js
. This is probably due to the dynamic import of the migration module by the library itself and because webpack replaces how require
loads modules.
How can I configure Webpack that it registers the migration js files in it's build, so when the library calls the require it will be able to retrieve the modules.
Library tries requires the module in the following absolute path strategy:
// Roughly
path.join(pwd(), migrationsDir, fileName)
Error received
Could not migrate up [file-name]-migration.js. Cannot find module [absolute-path]/migrations/[file-name]-migration.js
Even though the file exists, tried multiple relative locations just to be sure.
State
I'm using Webpack for building Nest.js application and migrate-mongo
for migrations in an NX project. Migration files are located in migrations/
directory and migration up is triggered by application on startup. Migration works normally when app is started in development mode.
migrate.ts
// This function is executed on app bootstrap
export const migrate = async (): Promise<void> => {
Logger.log('[Migration]: Started');
config.set(createConfig());
const {db, client} = await database.connect();
const migrated = await up(db, client);
migrated.forEach((fileName) => {
Logger.log(`[Migration]: migrated ${fileName}`);
});
Logger.log('[Migration]: End');
};
webpack.config.js
module.exports = {
mode: 'development',
target: 'node',
entry: './src/main.ts',
module: {
rules: [
{
test: /\.ts?$/,
use: 'ts-loader',
exclude: [/node_modules/, /other-app/],
}
],
},
resolve: {
extensions: ['.ts', '.js'],
plugins: [
new TsconfigPathsPlugin({
configFile: path.resolve(__dirname, '../../tsconfig.json'),
}),
],
},
output: {
path: path.resolve(__dirname, '../../dist/apps/my-backend'),
filename: 'src/main.js',
},
externals: [
nodeExternals(),
],
plugins: [/* ... */],
}
Tried solutions
- Tried using CopyPlugin to copy the migrations, but as found out all modules are placed within the built bundle.
- Tried updating externals to include the directory with migrations
- Tried requiring or importing the file and directory in app to register the modules