ruby-on-rails - tailwind 3 未在 Rails + shakapacker + HAML 中完全加载(webpacker@v6、webpack@v5、postcss@v8)

标签 ruby-on-rails webpack tailwind-css haml postcss

更新 2021-09-08:TL;DR。 Tailwind 未应用于 HAML 模板。

将项目迁移到 shakapacker,它在底层使用 webpack@v6postcss。除了 TailwindCSS 之外,所有其他前端 CSS 资源似乎都已正确加载。

为了使调试更简单,我从主文件中删除了除 Tailwind 之外的所有其他 CSS 导入。我还创建了以下测试 HTML 页面来查看是否应用了 Tailwind CSS 样式。

test.html
...
<div class="max-w-sm rounded overflow-hidden shadow-lg">
  <div class="px-6 py-4">
  <div class="font-bold text-xl mb-2">
    The Coldest Sunset
  </div>
  <p class="text-gray-700 text-base">
      Lorem ipsum
    </p>
  </div>
</div>
...

当我查看此页面时,它看起来很简单,只有文本 - 没有应用阴影、填充、字体粗细等。当我查看生成的 CSS 输出时,似乎只加载了 Tailwind 的重置样式,没有加载其他内容。

您可以在此处查看输出:http://codebin.org/view/bba03ee2 .

2022 年 8 月 11 日更新

按照下面的评论建议,我运行了 yarn run tailwindcss -i ./app/assets/packs/styles/application.scss -o ./output.css 并产生了以下错误:

.../app/assets/packs/styles/application.scss:4:1: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser

该错误指向第一个注释掉的行: //@tailwind "base"; 这是有道理的,因为 //双正斜杠注释SASS/SCSS 功能,而不是标准 CSS

但是,我认为包含 sasssass-loader 可以根据 shakapacker 安装说明来处理此问题。

因此,我在 webpack.config.js 中明确指定了加载器(见下文),但错误仍然发生。

我已包含以下所有相关文件。

配置文件

application.scss(导入所有 CSS 资源):
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
// @tailwind "base";
// @tailwind "components";
// @tailwind "utilities";

使用@import@tailwind会产生相同的结果。

application.js(导入application.scss)

我只包含了相关的代码行。

...
import "./styles/application.scss"
...
packages.json
{
  "name": "app",
  "private": true,
  "dependencies": {
    "@babel/core": "7",
    "@babel/plugin-transform-runtime": "7",
    "@babel/preset-env": "7",
    "@babel/runtime": "7",
    "@rails/actioncable": "^7.0.3-1",
    "@rails/activestorage": "^7.0.3-1",
    "@rails/ujs": "^7.0.3-1",
    "babel-loader": "8",
    "coffee-loader": "^4.0.0",
    "coffeescript": "^2.7.0",
    "compression-webpack-plugin": "9",
    "jquery": "^3.6.0",
    "jquery-ujs": "^1.2.3",
    "moment": "^2.29.4",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-loader": "^7.0.1",
    "postcss-preset-env": "^7.7.2",
    "select2": "^4.1.0-rc.0",
    "shakapacker": "6.5.0",
    "tailwindcss": "^3.1.8",
    "terser-webpack-plugin": "5",
    "tributejs": "^5.1.3",
    "turbolinks": "^5.2.0",
    "webpack": "5",
    "webpack-assets-manifest": "5",
    "webpack-cli": "4",
    "webpack-dev-server": "^4.9.3",
    "webpack-merge": "5"
  },
  "version": "0.1.0",
  "babel": {
    "presets": [
      "./node_modules/shakapacker/package/babel/preset.js"
    ]
  },
  "browserslist": [
    "defaults"
  ],
  "devDependencies": {
    "autoprefixer": "^10.4.8",
    "css-loader": "^6.7.1",
    "mini-css-extract-plugin": "^2.6.1",
    "postcss": "^8.4.16",
    "sass": "^1.54.3",
    "sass-loader": "^13.0.2",
    "style-loader": "^3.3.1",
    "tailwindcss": "^3.1.8"
  }
}

webpack.config.js:
const { webpackConfig, merge } = require('shakapacker')

// See the shakacode/shakapacker README and docs directory for advice on customizing your webpackConfig.

const sassLoaderConfig = {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },
};

const options = {
  resolve: {
      extensions: ['.mjs', '.js', '.sass', ".scss", ".css", ".module.sass", ".module.scss", ".module.css", ".png", ".svg", ".gif", ".jpeg", ".jpg"]
  }
}

module.exports = merge(webpackConfig, sassLoaderConfig, options);
postcss.config.js
module.exports = {
  plugins: [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    })
  ]
}
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.html',
    './app/**/*.html.slim',
    './app/**/*.html.erb',
    './app/**/*.js'    
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
webpacker.yml
# Note: You must restart bin/webpacker-dev-server for changes to take effect

default: &default
  source_path: app/assets

  # You can have a subdirectory of the source_path, like 'packs' (recommended).
  # Alternatively, you can use '/' to use the whole source_path directory.
  source_entry_path: /packs

  # If nested_entries is true, then we'll pick up subdirectories within the source_entry_path.
  # You cannot set this option to true if you set source_entry_path to '/'
  nested_entries: true 

  public_root_path: public
  public_output_path: packs
  cache_path: tmp/webpacker
  webpack_compile_output: true
  # See https://github.com/shakacode/shakapacker#deployment
  webpacker_precompile: true

  # Location for manifest.json, defaults to {public_output_path}/manifest.json if unset
  # manifest_path: public/packs/manifest.json

  # Additional paths webpack should look up modules
  # ['app/assets', 'engine/foo/app/assets']
  additional_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Select loader to use, available options are 'babel' (default), 'swc' or 'esbuild'
  webpack_loader: 'babel'

  # Set to true to enable check for matching versions of shakapacker gem and NPM package - will raise an error if there is a mismatch or wildcard versioning is used
  ensure_consistent_versioning: false

  # Select whether the compiler will use SHA digest ('digest' option) or most most recent modified timestamp ('mtime') to determine freshness
  compiler_strategy: digest
  
  extract_css: true

development:
  <<: *default
  compile: true
  compiler_strategy: mtime

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    # Hot Module Replacement updates modules while the application is running without a full reload
    hmr: false
    # If HMR is on, CSS will by inlined by delivering it as part of the script payload via style-loader. Be sure
    # that you add style-loader to your project dependencies.
    #
    # If you want to instead deliver CSS via <link> with the mini-extract-css-plugin, set inline_css to false.
    # In that case, style-loader is not needed as a dependency.
    #
    # mini-extract-css-plugin is a required dependency in both cases.
    inline_css: true
    # Defaults to the inverse of hmr. Uncomment to manually set this.
    # live_reload: true
    client:
      # Should we show a full-screen overlay in the browser when there are compiler errors or warnings?
      overlay: true
      # May also be a string
      # webSocketURL:
      #  hostname: "0.0.0.0"
      #  pathname: "/ws"
      #  port: 8080
    # Should we use gzip compression?
    compress: true
    # Note that apps that do not check the host are vulnerable to DNS rebinding attacks
    allowed_hosts: "all"
    pretty: true
    headers:
      'Access-Control-Allow-Origin': '*'
    static:
      watch:
        ignored: '**/node_modules/**'

test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Cache manifest.json for performance
  cache_manifest: true

最佳答案

所以,经过一番寻找之后,罪魁祸首就在 tailwind.config.js 文件中。我没有提及我正在使用 HAML 模板,并且忘记将 *.haml 扩展添加到 tailwind 配置中。

我将更新原始问题,以便将 HAML 作为问题的一部分。

解决方案如下。

const plugin = require('tailwindcss/plugin')
module.exports = {
  content: [
    ...
    './app/views/**/*.html.haml',
    './app/views/**/*.haml',
    ...
  ],
  plugins: [
      ...
  ]
}

关于ruby-on-rails - tailwind 3 未在 Rails + shakapacker + HAML 中完全加载(webpacker@v6、webpack@v5、postcss@v8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73311322/

相关文章:

html - 如何在 Tailwind CSS 中通过边距填充更改占位符位置?

javascript - React/Next.js ,打开对话框后页面滚动卡住

HTML 删除文本之间所需的空格

ruby-on-rails - Rails 数据库/模型架构约定

ruby-on-rails - 由多个 Controller 和模型共享的代码——保存它的最佳位置在哪里?

ruby-on-rails - 我如何调用 Rake 中的另一个任务

gulp和webpack-dev-server,报错TypeError : this. sockWrite is not a function

javascript - 使用 Webpack 自动加载外部组件

css - 在 Tailwind CSS 中使暗模式 `background-image` 的渐变与亮模式下的简单背景 `background-color` 一起工作?

javascript - webpack:如何在node_modules中转译代码