在 nuxt 2 中使用 sugarss

Use sugarss with nuxt 2

我正在尝试在我的 nuxt 项目中使用 postcss sugarss syntax

我尝试了很多方法:

将特殊的 sss 规则推送到 config.module.rules(这是我更喜欢的)。

这基本上是我在 nuxt.config.tsbuild.extend 中尝试过的内容:

// earlier on at the top level I have this
css: [ '@/assets/css/main.sss' ],

extend(config) {
    config.module = config.module || { rules: [] }
    config.module.rules.push({
        test: /\.sss$/,
        use: [
            // 'vue-loader',
            // 'style-loader',
            // { loader: 'css-loader', options: { importLoaders: 1 } },
            'postcss-loader?parser=sugarss',
        ]
    })
}

此示例(仅 postcss-loader 实际参与)未成功将样式添加到呈现的页面。因此,例如这些文件:

/* tailwind.css */
@tailwind base;

@tailwind components;

@tailwind utilities;
// main.sss
@import './tailwind.css'

a
    color: green

链接不是绿色的,none tailwind 实用程序工作。

我知道 nuxt 正在 处理 那些文件,因为如果我在其中出现语法错误,构建就会失败。

取消注释任何其他装载程序对我尝试过的任何组合也无济于事,但我承认我只是在黑暗中射击。

我相当确信这种方法的问题在于我没有正确挂接到 nuxt webpack 样式的加载器链,但我不确定该怎么做。我看了这个boilerplate example from JGJP,但是他用的是nuxt 1.0版本,他导入的'nuxt/lib/builder/webpack/style-loader.js'文件已经不存在了。 Nuxt 在 packages/webpack/src/utils/style-loader.js 中有一些类似的概念,但我无法导入它们,而且我什至不确定这是否有帮助。

我也找不到任何人向 nuxt 添加非标准样式表语法的例子。

将我的 build.postcss.parser 设置为 sugarss,这会导致 normal css 在 .nuxt 目录等位置休息。

ERROR  in ./.nuxt/components/nuxt-loading.vue?vue&type=style&index=0&lang=css&

Syntax Error: SyntaxError
(157:16) Unnecessary curly bracket

  155 | 
  156 | 
> 157 | .nuxt-progress {
      |                ^
  158 |   position: fixed;
  159 |   top: 0px;

添加一个特殊的 postcss.config.js 文件到我的 src 目录,parser 设置为 sugarss,这样只有 my css 文件将以这种方式解析。但这不起作用,我 仍然 得到上述 .nuxt 错误,以及这些警告:

WARN  Please use build.postcss in your nuxt.config.js instead of an external config file. Support for such files will be removed in Nuxt 3 as they remove all defaults set by Nuxt and can cause severe problems with features like alias resolving inside your CSS.

WARN  You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js. 

第二个警告没有多大意义,因为 nuxt.build.postcss 配置和特殊目录配置都不是空的。

提前致谢!

我能够通过 console.log 将现有的 config.module.rules 传递给 extend(config) 并无耻地复制它来弄清楚。这是我最终得到的解决方案。

const vueStyle = { loader: 'vue-style-loader', options: { sourceMap: true } }
const css = {
    loader: 'css-loader',
    options: {
        sourceMap: true,
        importLoaders: 2,
        exportOnlyLocals: false
    }
}
const postcss = {
    loader: 'postcss-loader',
    options: {
        parser: 'sugarss',
        sourceMap: true,
        plugins,
        order: 'presetEnvAndCssnanoLast'
    }
}
const cssModule = {
    ...css,
    options: {
        ...css.options,
        localIdentName: '[local]_[hash:base64:5]',
        modules: true,
    },
}

config.module.rules.push({
    test: /\.sss$/,
    oneOf: [
        { resourceQuery: /module/, use: [vueStyle, cssModule, postcss] },
        { use: [vueStyle, css, postcss] },
    ],
})