代码之家  ›  专栏  ›  技术社区  ›  crmpicco

在Webpack配置中更改图像资产路径

  •  0
  • crmpicco  · 技术社区  · 5 年前

    我在Webpack/Encore上遇到问题,因为我的图像URL没有正确拉入。

    homepage.scss :

    body {
        background: #FFEFE2 url("../../img/bg.jpg") no-repeat;
    }
    

    生成的标记是:

    body {
        background: #FFEFE2 url(/build/images/bg.9f6bc44a.jpg) no-repeat;
    }
    

    我的应用程序位于 /app ,所以正确的URL应该是 /app/build/images/bg.9f6bc44a.jpg .

    我的Webpack Encore配置:

    var Encore = require('@symfony/webpack-encore');
    
    Encore
    // directory where compiled assets will be stored
        .setOutputPath('web/build/')
        // public path used by the web server to access the output path
        .setPublicPath('/build')
    
        /*
         * ENTRY CONFIG
         *
         * Add 1 entry for each "page" of your app
         * (including one that's included on every page - e.g. "app")
         *
         * Each entry will result in one JavaScript file (e.g. app.js)
         * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
         */
        .addEntry('app', './web/assets/js/app.js')
    
        // will require an extra script tag for runtime.js
        // but, you probably want this, unless you're building a single-page app
        .enableSingleRuntimeChunk()
    
        .cleanupOutputBeforeBuild()
    
        .enableSourceMaps(!Encore.isProduction())
    
        // enables hashed filenames (e.g. app.abc123.css)
        .enableVersioning(Encore.isProduction())
    
        // uncomment if you use Sass/SCSS files
        .enableSassLoader()
    
        // uncomment if you're having problems with a jQuery plugin
        .autoProvidejQuery()
    ;
    
    module.exports = Encore.getWebpackConfig();
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   crmpicco    5 年前
    Encore
       // directory where compiled assets will be stored
       .setOutputPath('web/build/')
       // public path used by the web server to access the output path
       .setPublicPath('/app/build')
       // only needed for CDN's or sub-directory deploy
       .setManifestKeyPrefix('build/')
    

    只需更改当前路径和 setManifestKeyPrefix .

        2
  •  0
  •   Zamir    5 年前

    你可以用复印件 Webpack Plugin . 将其添加到依赖项后,更改 webpack.config.js如下:

    const CopyWebpackPlugin = require('copy-webpack-plugin');
    
    .addEntry('app', './assets/js/app.js')
    .....
    .addPlugin(new CopyWebpackPlugin([
            // copies to {output}/static
            { from: './assets/static', to: 'static' }
        ]))
    ;
    

    重新启动Encore后,您可以使用如下图像:

    <img src="{{ asset('build/static/foo.jpg') }}" />