Allow to disable Webpack bundling for NestJS apps #8482
Replies: 27 comments 23 replies
-
This is a very good question, also I wanted to use nx for my project but I would like to avoid compiling through webpack. |
Beta Was this translation helpful? Give feedback.
-
Just started looking at using nx for a nestjs project, but without separate entity files produced in the dist I don't see how this helps when trying to run migrations for deploying to productions. Seems like a non-starter for my case. |
Beta Was this translation helpful? Give feedback.
-
Nx has such a strong Angular focus, and I think the core developers are mostly Angular developers. Considering that Next is quickly becoming (if not has become) the mainly used framework for web development, I'd love to see better overall support and work with Next. |
Beta Was this translation helpful? Give feedback.
-
Any update here? |
Beta Was this translation helpful? Give feedback.
-
Is there any update? |
Beta Was this translation helpful? Give feedback.
-
I would also like to see this implemented |
Beta Was this translation helpful? Give feedback.
-
Any update guys? |
Beta Was this translation helpful? Give feedback.
-
Is there any update ? |
Beta Was this translation helpful? Give feedback.
-
Is there any update? |
Beta Was this translation helpful? Give feedback.
-
+1 bump for this, lets keep webpack out of the backend side, please |
Beta Was this translation helpful? Give feedback.
-
+1 really need this feature! |
Beta Was this translation helpful? Give feedback.
-
+1 really need it |
Beta Was this translation helpful? Give feedback.
-
I did build a wicked (feels brittle but I am still kinda proud) solution. I explicitly added "pluginsConfig": {
"@nx/js": {
"analyzeSourceFiles": true
}
} to "executor": "@nx/js:tsc",
"outputs": [
"{options.outputPath}"
],
"defaultConfiguration": "production",
"options": {
"generatePackageJson": true,
"generateLockfile": true,
"updateBuildableProjectDepsInPackageJson": true,
"buildableProjectDepsInPackageJsonType": "dependencies",
...
} which produces How did I solve the struggle with the internal libs? I am using pnpm as a package manager and was able to use its linking. You could either set the link in the version of your libs cat package.json | jq '.dependencies = ( .dependencies | to_entries | map(if .key | startswith("@YOURSCOPE/") then .value = "link:./libnx/\(.key|sub("^@YOURSCOPE/"; ""))" else . end) | from_entries )' | tee package.json Important... make sure to copy the libs from dist to your docker image as well. Happy to receive some feedback! :) |
Beta Was this translation helpful? Give feedback.
-
Any official support to eject webpack from nestjs? Webpack has been causing havoc on our apps |
Beta Was this translation helpful? Give feedback.
-
Regarding referencing migration files, there is an rather straightforward workaround. // ... Imports
@Injectable()
export class TypeOrmProvider implements TypeOrmOptionsFactory {
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
return {
type: "postgres",
host: "foo",
port: 5432,
username: "foo",
password: "foo",
migrations: [
InitialChangelog1706807759398,
RefactorChangelog1707389887104,
AddColumn1707410043409,
// Reference all migrations that should run here
],
};
}
} It's a bit tedious to do that with every migration, but meh. Better than anything else, I've come around so far. |
Beta Was this translation helpful? Give feedback.
-
I think the best idea (for now) is to update documentation to showcase how to chain the @nx/js:tsc executor to compile specific folders like "migrations", and place them in the final output. |
Beta Was this translation helpful? Give feedback.
-
Are there any official updates? |
Beta Was this translation helpful? Give feedback.
-
any updates on this? |
Beta Was this translation helpful? Give feedback.
-
Are there any updates? +1 |
Beta Was this translation helpful? Give feedback.
-
Are there any updates? |
Beta Was this translation helpful? Give feedback.
-
You can already replace webpack with swc/tsc using the executors nx provides.
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
},
"target": "es2020",
"externalHelpers": true,
"keepClassNames": true
},
"module": {
"type": "commonjs"
},
"sourceMaps": true,
"exclude": [
"jest.config.ts",
".*\\.spec.tsx?$",
".*\\.test.tsx?$",
"./src/jest-setup.ts$",
"./**/jest-setup.ts$",
".*.js$"
]
}
{
"name": "backend",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/backend/src",
"projectType": "application",
"targets": {
"build": {
"executor": "@nx/js:swc",
"options": {
"outputPath": "dist/apps/backend",
"main": "apps/backend/src/main.ts",
"tsConfig": "apps/backend/tsconfig.app.json",
"assets": ["apps/backend/src/assets"]
}
},
"serve": {
"executor": "@nx/js:node",
"options": {
"buildTarget": "backend:build"
}
}
},
"tags": []
}
|
Beta Was this translation helpful? Give feedback.
-
I've found a pretty elegant solution to team Webpack with dynamically imported files like migrations. In my case I wanted Webpack to dynamically import migration files for TypeORM. Step 1: Install typings for Webpack's npm i -D @types/webpack-env Step 2: Add types inside your app's {
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["node", "@types/webpack-env"], // notice "@types/webpack-env" is added in "types" array
"emitDecoratorMetadata": true,
"target": "es2021"
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
} Step 3: Dynamically import migrations when registering TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<AppEnvironment, true>) => ({
type: 'postgres',
host: config.get('PG_HOST'),
port: config.get('PG_PORT'),
schema: config.get('PG_SCHEMA'),
username: config.get('PG_USERNAME'),
password: config.get('PG_PASSWORD'),
autoLoadEntities: true,
migrations: (() => {
// Create an import context by specifying a relative path to `migrations` folder with a filter by file name ending with `.ts`
const context = require.context('./migrations', true, /\.ts$/);
// `context.keys()` returns a list of keys for dynamically imported modules within your bundle.
// `context(key) returns contents of imported module
// `context(key).default` returns an `export default` thing of imported module (in my case that's migration class)
return context.keys().map((key) => context(key).default);
})(),
migrationsRun: true,
logging: 'all',
}),
}), Step 4: Adding migrations I add migrations manually in A typical migration file looks like this: File name: File contents: import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export default class CreateUserTable1727300953457 // <-- notice usage of `export default` because I configured `require.context` to take `default` export
implements MigrationInterface
{
async up(runner: QueryRunner) {
await runner.createTable(
new Table({
name: 'user',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
isGenerated: true,
generationStrategy: 'uuid',
},
],
}),
true
);
}
async down(runner: QueryRunner) {
await runner.dropTable('user', true);
}
} Thats it. Now, when Webpack assembles an application it will find your migrations (or other files) with a hint you provided using Afterword Webpack is a good tool and there's certainly a value in using it. |
Beta Was this translation helpful? Give feedback.
-
So here is my two cent, I did ditch the entire webpack. IDK why Nx is using it so intensely everywhere you can think of. Maybe they have their own reasons but I also have mine to just remove this dep from my backend app. I am usig ExpressJS and to build my app I used this little trick: {
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"parallel": false,
"commands": [
{
"command": "npx tsc --incremental --project ./apps/api/tsconfig.app.json"
}
]
},
"outputs": ["{workspaceRoot}/dist/out-tsc/apps/api/src/"]
},
}
} And I do not touch the auto generated Here is my repo: https://github.com/kasir-barati/react/blob/45c7e4b9f1e097299a3188d042df5e363eaba728/apps/api/project.json#L8-L19 I have also used this approach in NestJS and it works there too. If this helped you in anyway please consider giving my repo a star. |
Beta Was this translation helpful? Give feedback.
-
Webpack bundles the whole NestJS app into a single file. But the output misses dynamically discovered, imported, and executed files, like database migrations.
Please add an option to disable Webpack and output just compiled .ts files.
More about the
webpack: boolean
in NestJS CLI config - https://docs.nestjs.com/cli/monorepo#global-compiler-optionsAs I understand, it does a "compiler" switching based on this flag between
webpack
andtsc
.UPD 2024-10-03: Consider the approach in reply
Beta Was this translation helpful? Give feedback.
All reactions