Vladimír Paraska
Vladimír Paraska

Reputation: 47

Webpack: How to rewrie URL in .css

For 3 days straight I am having a trouble to setup Webpack for staging purposes. The goal is to rewrite url of assets in final .css file (frontend.css) like this:

Let's say that in .scss file I have:

background: url('/assets/image.png') (this works for dev and prod)

and in final outputted .css file for staging, I want it to be:

background: url('https://stage.domain.com/staging/project-name/assets/image.png')

I have script npm run stage, that build js. and .css only for staging puposes. It creates stage dir on root with two files frontened-bundle.js and frontend.css. (see bottom of "Files structure" screenshot).

I tried to rewrite url with resolve-url-loader with root parameter, but I cant get it working. publicPath is also ignored.

I am not sure what I am doing wrong. Please point me in right direction.

Files structure:

enter image description here

webpack.stage.js:

const path = require('path');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
    const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
    const StyleLintPlugin = require('stylelint-webpack-plugin');
    
    const public_path = 'https://stage.domain.com/staging/project-name/'
    
    module.exports = {
      context: __dirname,
      entry: {
        frontend: [
          './src/js/index.js',
          './src/scss/main.scss'
        ],
        // customizer: './src/customizer.js'
      },
      resolve: {
        extensions: ['.ts', '.js', '.jsx', '.scss', '...',],
      },
      output: {
        path: path.resolve(__dirname, 'stage'),
        publicPath: public_path,
        filename: '[name]-bundle.js'
      },
      mode: 'production',
      // devtool: 'cheap-eval-source-map',
      module: {
        rules: [
          {
            enforce: 'pre',
            exclude: /node_modules/,
            test: /\.jsx$/,
            loader: 'eslint-loader'
          },
          {
            test: /\.jsx?$/,
            loader: 'babel-loader'
          },
          {
            test: /\.s?css$/,
            use: [
              {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  publicPath: public_path,
                  sourceMap: true
                }
              },
              {
                loader: 'css-loader',
                options: {
                  url: false,
                  sourceMap: true
                }
              },
              {
                loader: 'resolve-url-loader',
                options: {
                  // root: path.join(__dirname, './'),  // returns url("../../assets/assets/fonts/NewYork.woff2")
                  // root: '/',                         // returns url('../../../../../../assets/fonts/NewYork.woff2')
                  // root: './',                        // returns url('../../assets/fonts/NewYork.woff2')
                  attempts: 1,
                  debug: true,
                  sourceMap: true,
                  publicPath: public_path,
                },
              },
              {
                loader: 'sass-loader',
                options: {
                  sourceMap: true
                }
              },
            ]
          },
          {
            test: /\.(ttf|woff|woff2|eot|jpe?g|png|svg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[path][name].[ext]',
                  // outputPath: '../',
                  publicPath: publicPath,
                },
              },
              'img-loader',
              'url-loader',
            ]
          }
        ]
      },
      plugins: [
        // new StyleLintPlugin(),
        new MiniCssExtractPlugin({
          filename: '[name].css'
        }),
      ],
      optimization: {
        // minimizer: [new UglifyJsPlugin(), new OptimizeCssAssetsPlugin()]
      }
    };

package.json

{
  "name": "project_name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --mode=production",
    "dev": "webpack --watch",
    "stage": "npm run clean && webpack --config webpack.stage.js -p --progress --profile",
    "clean": "rm -rf stage"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "keywords": [
    "webpack"
  ],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "devDependencies": {
    "@babel/cli": "^7.14.5",
    "@babel/core": "^7.6.2",
    "@babel/preset-env": "^7.6.2",
    "autoprefixer": "^9.6.4",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "browser-sync": "^2.27.4",
    "browser-sync-webpack-plugin": "^2.2.2",
    "css-loader": "^3.2.0",
    "css-mqpacker": "^7.0.0",
    "eslint": "^6.5.1",
    "eslint-config-prettier": "^6.4.0",
    "eslint-config-wordpress": "^2.0.0",
    "eslint-loader": "^3.0.2",
    "eslint-plugin-prettier": "^3.1.1",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^4.2.0",
    "img-loader": "^3.0.1",
    "mini-css-extract-plugin": "^0.8.0",
    "node-sass": "^4.14.1",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "postcss-loader": "^3.0.0",
    "prettier": "^1.18.2",
    "resolve-url-loader": "^4.0.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "stylelint": "^11.0.0",
    "stylelint-config-recommended-scss": "^4.0.0",
    "stylelint-config-wordpress": "^15.0.0",
    "stylelint-order": "^3.1.1",
    "stylelint-scss": "^3.11.1",
    "stylelint-webpack-plugin": "^1.0.1",
    "svg-sprite-loader": "^4.1.6",
    "svgo": "^1.3.0",
    "svgo-loader": "^2.2.1",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "url-loader": "^4.1.1",
    "webpack": "^4.41.0",
    "webpack-cli": "^3.3.9",
    "wp-pot-cli": "^1.5.0"
  },
  "dependencies": {
    "@babel/polyfill": "^7.6.0",
    "imagemin": "^8.0.0",
    "jquery": "^3.6.0"
  }
}

Upvotes: 1

Views: 788

Answers (1)

dee
dee

Reputation: 2424

I've had this similar issue in the past, I tried the below from the docs,

const ASSET_PATH = process.env.ASSET_PATH || '/';

export default {
  output: {
    publicPath: ASSET_PATH,
  },

  plugins: [
    // This makes it possible for us to safely use env vars on our code
    new webpack.DefinePlugin({
      'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH),
    }),
  ],
};

But actually, the one that worked perfectly for my issue is below, while the public path was the CDN link from where the assets were served

  require('dotenv').config();
  __webpack_public_path__ = config.publicPath // publicPath is process.env.ASSET_PATH || '/';

When you set the publicPath as "../" did you also try the useRelativePaths: true?

Ref:- https://github.com/webpack-contrib/file-loader#userelativepath

Upvotes: 1

Related Questions