4

在 webpack 中使用 postcss-loader(带有 postcss-modules)时,我为每个带有 css-module 哈希映射的 .scss 文件获得一个 .json 文件。如果我将 css-loader 与 一起使用modules: true,我不会得到这样的映射文件。是否也可以使用该装载机获得一个?

问题实际上是在使用 postcss-loader 时,由于某种原因,我不能在我的 .js 文件中导入 scss 文件。如果我改用 css-loader,那是可能的。

我需要在我的 .js 文件中导入 scss 文件并正确导入 css-modules,并生成我在我的 php 文件中使用的映射文件 (.json)。

4

1 回答 1

0

我使用css-loader.

最后,我可以使用postcss-modulesposthtml-css-modules

首先,postcss-modules将 .css/.scss 文件转换为 base64 中的哈希。此外,它会.json为每个 .css/.scss 文件创建文件,其中包含每个类名到其对应哈希名的映射。

然后,posthtml-css-modules获取使用 .css/.scss 文件的 html 文件,并将使用名为 with 的类的 html 元素转换为在 .css 中css-modules定义的相应哈希名称.json

webpack.config.js


module.exports = function (options) {
    ...
    return {
       ...
       module: {
            rules: [
                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
                    loader: '@ngtools/webpack'
                },
                {
                    test: /\.html$/,
                    use: [
                        {
                            loader: 'html-loader'
                        },
                        {
                            loader: 'posthtml-loader',
                            options: {
                              config: {
                                ctx: {
                                  include: {...options},
                                  content: {...options}
                                }
                              }
                            }
                        }
                    ],
                    exclude: [helpers.root('src/index.html')]
                },
                {
                    test: /\.(css|sass|scss)$/,
                    exclude: [helpers.root('src', 'styles')],
                    use: [
                        'to-string-loader',                  
                        'css-loader',
                        'postcss-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.(jpg|png|gif|svg)$/,
                    loader: 'file-loader',
                    options: {
                        name: 'assets/[name].[hash].[ext]',
                    }
                },
                {
                    test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
                    use: 'file-loader'
                }

            ],
        },
    };
};

postcss.config.js

module.exports = {
    plugins: [
        require('autoprefixer'),
        require("postcss-modules")({
            generateScopedName: "[hash:base64:5]"
        })
    ]
}

posthtml.config.js

module.exports = ({ file, options, env }) => ({
    plugins: [
        require('posthtml-css-modules')(file.dirname.concat('/').concat(file.basename.replace('.html','.scss.json')))
      ]  
});
于 2020-03-04T21:10:27.270 回答