如何在NestJS中使用TailwindCSS?

3
我喜欢在我的React和Laravel项目中使用Tailwind CSS。
现在我开始学习NestJS,我想在我的项目中使用Tailwind CSS,但是我无法做到。
由于在Google上找不到任何结果,所以我向大家求助。
如果您能提供任何资源或详细的答案,我将不胜感激。
我的项目当前状态如下。我不知道哪里出错了,TailwindCSS无法工作。
请注意,我刚开始学习NestJS。

main.ts

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(3000);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

app.controller.ts

import { Controller, Get, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [],
})
export class AppModule {}

tailwind.config.js

module.exports = {
  content: ['./views/*.hbs', './views/**/*.hbs'],
  theme: {
    extend: {},
  },
  plugins: [],
};

webpack-hmr.config.js

const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');

module.exports = function (options, webpack) {
  return {
    ...options,
    //entry: ['webpack/hot/poll?100', options.entry],
    entry: './src/main.ts',
    externals: [
      nodeExternals({
        allowlist: ['webpack/hot/poll?100'],
      }),
    ],
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            { loader: 'style-loader' },
            {
              loader: 'css-loader',
              options: {
                modules: true,
              },
            },
          ],
        },
        {
          test: /\.ts$/,
          use: [{ loader: 'ts-loader' }],
        },
      ],
    },
    plugins: [
      ...options.plugins,
      new webpack.HotModuleReplacementPlugin(),
      new webpack.WatchIgnorePlugin({
        paths: [/\.js$/, /\.d\.ts$/],
      }),
      new RunScriptWebpackPlugin({ name: options.output.filename }),
    ],
  };
};

index.hbs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>NestJS App With TailwindCSS</title>
    <link rel="stylesheet" href="/assets/css/tailwind.css">
  </head>
  <body>
    <header class="w-full px-8 text-gray-700 bg-white flex">
      <h1 class="bg-slate-200">
      {{ message }}
      </h1>
    </header>
  </body>
</html>

and script command

"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch",

NestJS是一个后端框架,而Tailwind是一个前端CSS框架。你在说什么?你是不是指的是Next.js - undefined
不,我说的是 NestJS 而不是 NextJS。 所以,AdonisJS 是一个后端框架,但是也可以使用 tailwindcss。例如:https://www.cbsofyalioglu.com/code/adonisjs5-tailwind/如果有类似这样的解决方案适用于 NestJS,那将非常棒。 - undefined
为什么你不在 Nest 中使用相同的设置呢?看起来好像没有任何东西与 Adonis 相关联。只是一个 postcss 处理器和一个用于转译的 webpack 文件而已。我有什么遗漏吗? - undefined
1
@JayMcDoniel 我在我的第一篇帖子中添加了示例代码。我不明白为什么TailwindCSS不起作用。 - undefined
嘿,Mehmet,你解决它的方案了吗? - undefined
1个回答

1
我解决了同样的问题,但是我没有使用Webpack,它也能正常工作。
以下是我采取的步骤:
使用您喜欢的软件包管理器安装Tailwind。
npm install -D tailwindcss
npx tailwindcss init

因为Tailwind只会查找HTML文件中的类,所以我将在配置中限制它只在hbs文件中查找类,像这样:
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./views/*.hbs', './views/**/*.hbs'],
  theme: {
    extend: {},
  },
  plugins: [],
};

喜欢你配置的方式,我在根目录下创建了一个名为assets的文件夹,并在其中创建了一个tailwind.css文件。

assets/tailwind.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

然后我使用了这个tailwind CLI命令来构建并提取CSS到我的public目录中:
npx tailwindcss -i ./assets/tailwind.css -o ./public/main.css

注意:你不能在一个终端中同时使用热重载(--watch)和运行后端(nest start),所以将你的package.json配置成这样是行不通的:
"start:dev": "nest start --watch && npx tailwindcss -i ./assets/tailwind.css -o ./public/css/main.css --watch"
现在最后一步是将main.css文件引用到你的hbs文件中:

<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/main.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-7xl">
    Hello world
  </h1>
</body>
</html>

我建议先使用Next.js开发前端,然后打包和导出,再与后端集成。

完美运作,我需要这个来构建简单的管理面板。NextJS和它的伙伴们真是让人头疼。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接