【问题标题】:Webpack sass change background url to base64Webpack sass 将背景 url 更改为 base64
【发布时间】:2023-03-13 04:26:01
【问题描述】:

我有这个 Angular 应用程序,我的所有组件都嵌入了 sass 样式,我使用 .NET Core Angular 默认样板和 sass-loader 作为我的 sass 编译器。

  • 知道如何将 background-url 更改为 base 64。
  • 您对使用什么加载器有什么建议吗?

例如:

body.login-page:not(.dashboard-pages) {
    background-image: url(/images/atc-crowd.png) <- This one to base64;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    width: 650px;
    margin: 7% auto;

}

这是我当前的 webpack 配置。

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

function srcPath(subdir) {
    return path.join(__dirname, "ClientApp", subdir);
}

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = true;
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: {
            extensions: ['.js', '.ts'],
            alias: {
                "@app/common": srcPath("app/common"),
                "@app/core": srcPath("app/infrastructure/core.module/providers"),
                "@app/data": srcPath("app/infrastructure/data.module/index.ts"),
                "@app/shared": srcPath("app/infrastructure/shared.module/index.ts")
            }
        },
        output: {
            filename: '[name].js',
            chunkFilename: isDevBuild ? '[name].js' : '[name].[chunkhash].js',//If production mode, add hashes to the lazy loading modules
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, include: /ClientApp/, use: isDevBuild ?
                        ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : ['@ngtools/webpack', 'angular2-router-loader']

                },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                {
                    test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'

                },
                {
                    test: /\.scss$/,
                    exclude: /node_modules/,
                    loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
                }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AngularCompilerPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: {
            mainFields: ['main'],
            alias: {
                "@app/common": srcPath("app/common"),
                "@app/core": srcPath("app/infrastructure/core.module/providers"),
                "@app/data": srcPath("app/infrastructure/data.module/index.ts"),
                "@app/shared": srcPath("app/infrastructure/shared.module/index.ts")
            }
        },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

【问题讨论】:

    标签: javascript angular webpack sass


    【解决方案1】:

    您可以使用base64-inline-loader。这应该做你想要的。 你可以用这个替换你的图像规则。

    {
        test: /\.(jpe?g|png|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        use: 'base64-inline-loader?limit=1000&name=[name].[ext]'
    }
    

    但是您当前的url-loader 也应该将图像转换为base64。您已经配置了一个限制,之后使用普通的file-loader。你可以试试看是否有帮助。

    【讨论】:

    • 试过这个但是不行,因为sass是直接嵌入到组件中的,不会产生css文件。
    • 但是你的 sass 会从 webpack 中兼容 css,对吧?如果这有效,则图像加载也应该有效。我刚刚注意到您使用的是图像的绝对路径,它必须是相对的。尝试改变它。
    【解决方案2】:

    我为我找到了另一种方式:“postcss-loader”和“postcss-image-inliner”。

    {
        test: /\.scss$/,
        exclude: [/node_modules/, /dist/],
        use: [
          'style-loader',
          {
            loader: 'file-loader',
            options: { outputPath: '../css/', name: '[name].css'}
          },
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  ['postcss-image-inliner', {
                    maxFileSize: 1024000,
                    assetPaths: [path.resolve(__dirname + '/img')]
                    }],
                ],
              },
            },
          },
          'sass-loader'
        ]
      }
    

    有一个排除:如果你写规则

        background-image: url('../img/image.png');
    
    • 没关系,但如果你写

        background: url('../img/image.png') center center no-repeat;
      
    • 此行可能无法正常工作。小心点。

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 2019-12-20
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多