I want to serve static HTML files which are in a /dist
folder outside of the Nest project. index.html
is loaded successfully but it fails to load any JS file (404
error).
I have a Node/Express.js project which uses
app.use('/', express.static('../client/dist'))
and it works perfectly fine.
In the Nest project, however,
app.setBaseViewsDir(join(__dirname, '../../client/dist'))
does not do the trick.
In the AppController
I tried
import { Response } from 'express';
@Get()
get(@Res() res: Response) {
res.sendFile('index.html', {
root: '../client/dist',
});
}
But no luck.
As mentioned, the index.html
is loaded successfully. So the problem is not a wrong path. Neither is the problem wrong src-paths in the index.html
because in the Express project the exact same files are used.
/dist
|-index.html
|-main.js
|-etc.
In the index.html:
<script type="text/javascript" src="main.js"></script>
It does not work either when I put the dist folder into the Nest project (and adapt the path).
I use the express module now:
import * as express from 'express';
...
app.use('/', express.static('../client/dist'));
For serving static files you have to use useStaticAssets()
instead of setBaseViewsDir()
:
app.useStaticAssets(join(__dirname, '../../client/dist'))
When you use useStaticAssets
you don't need to set up a controller, all your files will be served automatically:
Let's say under client/dist
you have the files index.html
and pic.jpg
.
They will be served as:
localhost:3000 -> index.html
localhost:3000/pic.jpg -> pic.jpg
Setting the base views dir is needed when you want to use a view engine like for example hbs
, see docs.
Regarding the official documentation of Nest.js one should serve static files like this:
Install the required package:
npm install --save @nestjs/serve-static
Update app.module.ts to look like this:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'client'), // <-- path to the static files
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With