The official doc (https://docs.nestjs.com/recipes/swc) goes through SWC setup in Nest.js pretty well. But usually when we setup our Nest.js project with Docker, I try to get SWC working and here are thoughts around it. SWC is a little tricky because its package (in Rust) requires platform-native building.
As an example, I have a similar setup in this overall repo https://github.com/chat-stack/chat-stack using Nest.js and SWC. I will use code pointers from there.
When I install SWC it is in my Mac environment, and it works. But in Docker it doesn't. In Docker it actually needs the Docker's OS's SWC package.
My Docker runs on Alpine linux (https://github.com/chat-stack/chat-stack/blob/main/docker-compose.yml#L17)
Here is my "hack" fix:
- Add 2 more pkgs to dev dependencies in
package.json
{
"devDependencies": {
"@swc/core-linux-arm64-musl": "^1.3.95",
"@swc/core-linux-x64-musl": "^1.3.95",
}
}
This may be redundant but adding it for both arch will work to run my Docker in both arch. These two works for Alpine Linux in my Docker.
- Add optional dependencies and it will automatically figure out when I install it outside docker
{
"optionalDependencies": {
"@swc/core-darwin-arm64": "^1.3.95",
"@swc/core-darwin-x64": "^1.3.95",
"@swc/core-linux-arm-gnueabihf": "^1.3.95",
"@swc/core-linux-arm64-gnu": "^1.3.95",
"@swc/core-linux-x64-gnu": "^1.3.95",
"@swc/core-win32-arm64-msvc": "^1.3.95",
"@swc/core-win32-ia32-msvc": "^1.3.95",
"@swc/core-win32-x64-msvc": "^1.3.95"
}
}
Other points worth attention
volume mapping in
docker-compose.yml
(https://github.com/chat-stack/chat-stack/blob/main/docker-compose.yml#L17)- This should map the root folder.
baseUrl and path should match in
.swcrc
(https://github.com/chat-stack/chat-stack/blob/main/.swcrc#L10-L13)rootDir and baseUrl should match in
tsconfig.json
(https://github.com/chat-stack/chat-stack/blob/main/tsconfig.json#L14-L15)Consider using Eslint to prevent relative imports (https://github.com/chat-stack/chat-stack/blob/main/.eslintrc.js#L27)