webpack/css-loader

loaderContext.utils is "undefined", Causes a report that the "contextify" attribute cannot be read from "undefined".

Closed this issue · 1 comments

Bug report

Actual Behavior

releases:
css-loader@7.1.0

File reporting errors:
css-loader/dist/utils.js

The line of code that reported the error:
https://github.com/webpack-contrib/css-loader/blob/master/src/utils.js#L17

code:

function stringifyRequest(loaderContext, request) {
  return JSON.stringify(
    loaderContext.utils.contextify(
      loaderContext.context || loaderContext.rootContext,
      request,
    ),
  );
}

error message:
loaderContext.utils is "undefined", Causes a report that the "contextify" attribute cannot be read from "undefined".

Expected Behavior

In the "css-loader@6.11.0" version, there is no error in using it.
code:

// TODO simplify for the next major release
function stringifyRequest(loaderContext, request) {
  if (
    typeof loaderContext.utils !== "undefined" &&
    typeof loaderContext.utils.contextify === "function"
  ) {
    return JSON.stringify(
      loaderContext.utils.contextify(
        loaderContext.context || loaderContext.rootContext,
        request
      )
    );
  }

  const splitted = request.split("!");
  const { context } = loaderContext;

  return JSON.stringify(
    splitted
      .map((part) => {
        // First, separate singlePath from query, because the query might contain paths again
        const splittedPart = part.match(/^(.*?)(\?.*)/);
        const query = splittedPart ? splittedPart[2] : "";
        let singlePath = splittedPart ? splittedPart[1] : part;

        if (isAbsolutePath(singlePath) && context) {
          singlePath = path.relative(context, singlePath);

          if (isAbsolutePath(singlePath)) {
            // If singlePath still matches an absolute path, singlePath was on a different drive than context.
            // In this case, we leave the path platform-specific without replacing any separators.
            // @see https://github.com/webpack/loader-utils/pull/14
            return singlePath + query;
          }

          if (isRelativePath(singlePath) === false) {
            // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
            singlePath = `./${singlePath}`;
          }
        }

        return singlePath.replace(/\\/g, "/") + query;
      })
      .join("!")
  );
}

How Do We Reproduce?

This is a mistake that is bound to occur in development mode!

Please paste the results of npx webpack-cli info here, and mention other relevant information

css-loader/dist/utils.js

Answered in style-loader, please update webpack to the latest version (in fact it is not necessary to update to the latest version, but your webpack version is not compatible with this version of the loader)