Simple url loader wrapper ошибка

@nornagon It doesn’t look like anyone is actively working on electron-updater. Lots of apps are using it and 0476eb6 broke update for those apps. This should probably get some priority since most app authors likely won’t notice this until thousands of users are stranded with apps that no longer update. Would be great if you can help investigate and revert your change until this bug is understood and fixed?

  1. doDownload in httpExecutor.
  2. createRequest in electronHttpExecutor with redirect: "manual".
  3. addRedirectHandlers adds on("redirect") but request.followRedirect() is never called. Instead request.abort() is called starting another doDownload with the new location.
  4. The second doDownload gets a 200 response and the file is downloaded in the right location but Error: Redirect was cancelled is raised causing the whole update to fail.
  addRedirectHandlers(request, options, reject, redirectCount, handler) {
    request.on("redirect", (statusCode, method, redirectUrl) => {

      // no way to modify request options, abort old and make a new one
      // https://github.com/electron/electron/issues/11505
      request.abort();

      if (redirectCount > this.maxRedirects) {
        reject(this.createMaxRedirectError());
      } else {
        handler(_builderUtilRuntime().HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options));
      }
    });
  }
Error: Error: Redirect was cancelled
    at SimpleURLLoaderWrapper.<anonymous> (electron/js2c/browser_init.js:2561:23)
    at SimpleURLLoaderWrapper.emit (events.js:203:13)
(node:59127) UnhandledPromiseRejectionWarning: Error: Redirect was cancelled
    at SimpleURLLoaderWrapper.<anonymous> (electron/js2c/browser_init.js:2561:23)
    at SimpleURLLoaderWrapper.emit (events.js:203:13)
(node:59127) UnhandledPromiseRejectionWarning: Error: Redirect was cancelled
    at SimpleURLLoaderWrapper.<anonymous> (electron/js2c/browser_init.js:2561:23)
    at SimpleURLLoaderWrapper.emit (events.js:203:13)
(node:59127) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:59127) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:59127) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:59127) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

SimpleURLLoaderWrapper should probably not die with an error if request.abort() was called by the handler:

0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 390)     this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 391)       const { statusCode, newMethod, newUrl } = redirectInfo
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 392)       if (this._redirectPolicy === 'error') {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 393)         this._die(new Error(`Attempted to redirect, but redirect policy was 'error'`))
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 394)       } else if (this._redirectPolicy === 'manual') {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 395)         let _followRedirect = false
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 396)         this._followRedirectCb = () => { _followRedirect = true }
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 397)         try {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 398)           this.emit('redirect', statusCode, newMethod, newUrl, headers)
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 399)         } finally {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 400)           this._followRedirectCb = null
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 401)           if (!_followRedirect) {
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 402)             this._die(new Error('Redirect was cancelled'))
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 403)           }
0476eb67ab (Jeremy Apthorp 2019-12-02 12:26:47 -0800 404)         }

I am trying to import the image in my React code like so (I’m using babel):

import borgCube from '../assets/cube.png';

<img className="img-rounded" src={borgCube}></img><p />

What I see when I inspect the broken image in the browser:

<img class="img-rounded" src="data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICI5NTU1ZGJiNWQ3YjUzMjA3N2NjNWQyMzc4ZDgzNzVmZS5wbmciOw==">

It used to work until I added in css-modules. This is what my webpack config looks like:

var webpack = require('webpack');
var path = require('path');
var combineLoaders = require('webpack-combine-loaders');

const isDebug = !process.argv.includes('--release');

module.exports = {
  devtool: 'eval',

  entry: {
    app: [
      'webpack-dev-server/client?http://0.0.0.0:3000',
      'webpack/hot/only-dev-server',
      './src/index'
    ]
  },

  output: {
    filename: '[name].js',
    path: path.join(__dirname, './build'),
    publicPath: 'http://localhost:3000/build/'
  },

  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png'],
    modulesDirectories: ['src', 'node_modules']
  },

  module: {
    loaders: [
      {
        test: /.(js|jsx)$/,
        loaders: ['react-hot', 'babel'],
        exclude: /node_modules/
      },
    { test: /.(woff|png)$/, loader: 'url-loader?limit=10000' },
    { test: /.(png|jpg)$/, loader: 'file-loader'},

    {
        test: /.css$/,
        loader: combineLoaders([
          {
            loader: 'style-loader'
          }, {
            loader: 'css-loader',
            query: {
              modules: true,
              localIdentName: '[name]__[local]___[hash:base64:5]'
            }
           }
          ])
      },
    ]

  },


  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
    })
  ]

};

Добрый день. В общем, такая беда, url-loader возвращает кривой base64.

require('url?limit=10000!./resources/images/obladaet.jpg');

webpack conf

{ test: /.jpg$/,    loader: "url-loader?prefix=img/" },

И ещё вопрос: как url-loader использовать вместе со stylus?


  • Вопрос задан

    более трёх лет назад

  • 4895 просмотров

Привет. Как раз исользую stylus. У меня в конфиге вот так:

{ test: /.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }
{ test: /.styl$/, loader: "style-loader!css-loader!stylus-loader?paths[]=node_modules&paths[]=app" }

Картинки подключаю через стили, webpack сам кладет их в сборку.

.vusluk-logo
  background-image url(./logo.png)

Пригласить эксперта

test: /.jpg$/,    loader: "url-loader?name=img/[name].[ext]"


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

Кажется, что это css-loader ошибка и способ разрешения путей в @import и url(). Он пытается разрешить все пути — даже те из импортированных таблиц стилей — относительно основного файла CSS, что в вашем случае /Project_B/src/assets/stylesheets/index.scss.

Не плачь! Там есть решение!

Может быть, это не идеально, но это лучший, с которым я пришел. До сих пор.

Создать глобальную переменную $assetsPath, содержащую путь к активам относительно текущей таблицы стилей. Затем добавьте эту переменную ко всем вашим значениям url().

В вашем /Project_A/assets/stylesheets/index.scss вы должны написать:

/*/ Using !default we can override this variable even before the following line: /*/
$assetsPath: '../' !default;

.container {
    /*/ ... /*/
    .content-wrapper {
        /*/ ... /*/
        background-image: url($assetsPath + "images/content-bg.jpg");
    }
}

В вашем /Project_B/src/assets/stylesheets/index.scss вы должны написать:

/*/ The following variable will override $assetsPath defined in the imported file: /*/
$assetsPath: '../../../../Project_A/assets/';

/*/ Import Project A SCSS [Common Varibles, Classes, Styling etc] /*/
@import "../../../../Project_A/assets/stylesheets/index";

Последствия

Если вы связали Project-A с Gulp, он увидит код Project-A как:

        /*/ ... /*/
        background-image: url("../images/content-bg.jpg");

Хотя, когда вы связываете Project-B с Webpack, он увидит код Project-A как:

        /*/ ... /*/
        background-image: url("../../../../Project_A/assets/images/content-bg.jpg");

Поэтому вы сохраняетесь.

Скорее всего, я посмотрю на эту проблему поближе. Все это можно было бы избежать, если url-loader будет уважать путь в инструкции @import и соответствующим образом применять его к ссылочным активам. Либо я что-то упускаю, либо его следует рассматривать как ошибку.

Надеюсь, у вас чудесный день!
~ Wiktor

Cover image for Error: Resolve-Url-Loader : CSS error

Malek

Malek

Posted on Jun 28, 2020

• Updated on Jun 30, 2020



 



 



 



 



 

The famous Resolve Url Loader, a weird issue that I ran into while trying to run a react project for the first time on my newly installed development environment. If you are curious about all these details, you may refer to this article to read about the circumstances in which I ran into this error.

Alt Text

Of course, such errors would push you to start thorough and deep research on the web to know about the why and when and more importantly, the HOW solve it. I already did that, and after trying most of the suggestions, although they worked for some developers, they didn’t work in my case. The way I resolved this issue in my project was pretty unique, and that’s why I chose to share it in my blog.

I am glad you are here and I hope you find this content useful. Without further ado, let’s get to the solution!

since I was trying to run an existing project that I just clone from Github, I ran all the required commands such as :

  • Yarn install
  • Yarn upgrade
  • yarn add react-scripts
  • Yarn Build
  • Yarn start

Once I started the project this issue showed up every time, no matter what fixes I tried, so I went back to read the files line by line. Going through the Package.json file, I remarked that some of the packages weren’t upgraded, specifically the react-scripts package. It’s a set of scripts provided by the create-react-app starter pack, which enables launching React apps without much configuration. This capability comes in the form of multiple features, that include the auto prefixed CSS. And if you read the error details carefully, you will see that the issue is revealed on one of the CSS files. Of course, as part of the error investigation, I changed the CSS files links, I uninstalled, reinstalled, updated the node-sass and the resolve-URL-loader package, but to no avail.
To begin with, let’s discover the CSS Autoprefixer , what’s it, and what does it? and why is it stopping us from successfully building our newly created/cloned project?

What’s CSS AutoPrefixer?

It is a CSS post-processor that parses the compiled CSS files checking it against caniuse service to manage the prefixes related to each vendor.

What’s the Autoprefixer role?

It solves the problem we encounter with vendor prefixes that we have to apply to the CSS rules to make some options styles available for a larger variety of users on different browsers.
If that seems like a hard explanation, here it is short and clear: Autoprefixer is taking care of your CSS code, which prevents you from remeberance/add/remove/ check of vendor prefixes.

what’s the issue with the Autoprefixer?

when starting a new React project, you will need to install a react-scripts package, which includes the resolve-URL-loader package, the latter role includes management and redirection of the CSS files. connecting the dots, we may understand that the management operation of the CSS files includes the auto prefixing service. Previous versions of the resolve-URL-loader package used to make use of the Rework CSS parser, but as it’s not adapted to manage the modern CSS versions, the package of interest adopted the PostCSS parser by default. Long story short, the subject issue was the result of the bad configuration and management of CSS files caused by the Resolve-Url-Loader, itself included in the react-scripts package. Since my development environment was newly installed. I was using the latest version of yarn and upgrading all the packages, which caused the issue.

How I resolved the situation?

Reading the Package.Json file with a fine-tooth comb, I figured out that I was not using the same react-scripts that my team was using on the subject project. Uninstalling the existing react-scripts package and installing the right one served me well.

So here comes the end of my issues with the frontend project, that I built and start successfully. A sigh of satisfaction was about to rise from the bottom of my heart, but it didn’t, because the Backend project developed using C#, which was running flawlessly, was launching a new message error, that took almost two days to find a fix, and the solution, was not more common than the one described in this article.

Thank you for reading so far, and if you are willing to learn about the next bug with the .Net project, just click on the next article.

Понравилась статья? Поделить с друзьями:
  • Simcity ошибка обновления что делать
  • Simcity 5 ошибка msvcp120 dll
  • Simcity 2013 ошибка обновления попытайтесь еще раз
  • Sim карта код ошибки 34 xx что это
  • Sim карта для iphone ошибка