Skip to content

inline loader not migrateable to webpack 5 when used in require.context #12900

Closed

Description

@eps1lon

Bug report

What is the current behavior?

The documentation in https://webpack.js.org/guides/asset-modules/#replacing-inline-loader-syntax to replace inline loaders with Asset Modules does not apply to require.context. Specifically, it doesn't seem like I can exclude a source asset from being parsed by other loaders. This was possibly in webpack 4 with require.context("!raw-loader!./code", false, /\.js$/); but there seems to be no API for this behavior in webpack 5 i.e.

{
  test: /\.m?js$/,
  resourceQuery: /^(?!\?raw$).*/,
},
{
  resourceQuery: /raw/,
  type: "asset/source",
},
{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: ["babel-loader"],
},

does result in transpiled source assets.

If the current behavior is a bug, please provide the steps to reproduce.

  1. Clone https://github.com/eps1lon/webpack-asset-modules-source-require-context
  2. yarn install
  3. `yarn start´
  4. Open page

The source code is printed transpiled (notice the /*#__PURE__*/React.createElement transpilation artifact).

What is the expected behavior?

The source asset is not transpiled (or parsed by any other loader for that matter).

Other relevant information:
webpack version: 5.21.1
Node.js version: 12.20.0
Operating System: Ubuntu 20.04.2 LTS
Additional tools:

The issue seems similar to #5730?

Activity

  1. changed the title [-]inline loader not migrateable when used in require.context[/-] [+]inline loader not migrateable to webpack 5 when used in require.context[/+] on Mar 15, 2021
  2. alexander-akait commented on Mar 15, 2021

    @alexander-akait
    Member

    Intersect rules, please use:

    module: {
        rules: [
          {
            type: "asset/source",
            resourceQuery: /raw/,
          },
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            resourceQuery: /^(?!\?raw$).*/,
            use: ["babel-loader"],
          },
        ],
      },
    

    otherwise test is preferred

  3. added
    webpack-5
    on Mar 15, 2021
  4. eps1lon commented on Mar 15, 2021

    @eps1lon
    Author

    That's not what the documentation is saying though? Now I have to change any existing (and future) rule that might process assets loaded as source.

  5. alexander-akait commented on Mar 15, 2021

    @alexander-akait
    Member

    @eps1lon You need do it only for rules where test can have intersections (or where you don't specify test), maybe we should privatize resourceQuery and resourceFragment to improve DX

    /cc @sokra

  6. eps1lon commented on Mar 15, 2021

    @eps1lon
    Author

    @eps1lon You need do it only for rules where test can have intersections

    That's not adressing my problem though. I have to make sure anybody who adds rules considers this.

    How does you comment adress the problem where I don't have access to the rule objects e.g. when extending a nextjs webpack configuration?

  7. alexander-akait commented on Mar 15, 2021

    @alexander-akait
    Member

    maybe we should privatize resourceQuery and resourceFragment

    What about this? So you don't need exclude resourceQuery from other rules

  8. eps1lon commented on Mar 15, 2021

    @eps1lon
    Author

    maybe we should privatize resourceQuery and resourceFragment

    What about this? So you don't need exclude resourceQuery from other rules

    I'm not following. How would I then be able to migrate from inline-loaders? Based on file extension is not possible since I need some files both as regular JS and their raw source.

  9. alexander-akait commented on Mar 15, 2021

    @alexander-akait
    Member

    Sorry, I don't understand you.

    How would I then be able to migrate from inline-loaders?

    Using resourceQuery,

    Based on file extension is not possible since I need some files both as regular JS and their raw source.

    resourceQuery: /^(?!\?raw$).*/,

    I provide solution above.

    Do you want to avoid using resourceQuery: /^(?!\?raw$).*/,? If yes, above I suggested that we could prioritize resourceQuery over test, so you don't need resourceQuery: /^(?!\?raw$).*/, in your config

  10. eps1lon commented on Mar 15, 2021

    @eps1lon
    Author

    How would I then be able to migrate from inline-loaders?

    Using resourceQuery,

    But you said you want to "privatize ressourceQuery". I interpreted "privatize" as "not being part of the public API" i.e. not usable.

    Could you summarize how I would write the initial set of rules without changing the rule that applies the babel-loader?

  11. alexander-akait commented on Mar 15, 2021

    @alexander-akait
    Member

    @eps1lon sorry, typo, I mean prioritize

    Could you summarize how I would write the initial set of rules without changing the rule that applies the babel-loader?

    Right now only using resourceQuery: /^(?!\?raw$).*/,, we need think more about it

  12. sokra commented on Mar 15, 2021

    @sokra
    Member

    resourceQuery: /^(?!?raw$).*/

    That's pretty un-readable. You could use resourceQuery: { not: /raw/ }.

    But even better use oneOf rules:

    rules: [
      {
        oneOf: [
          {
            resourceQuery: /raw/,
            type: "asset/source",
          },
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: ["babel-loader"],
          },
        ]
      }
    ],

    write a helper function if this is too much nesting for you...

  13. eps1lon commented on Mar 16, 2021

    @eps1lon
    Author

    That's pretty un-readable. You could use resourceQuery: { not: /raw/ }.

    I just copied the docs 😅: https://webpack.js.org/guides/asset-modules/#replacing-inline-loader-syntax

    But even better use oneOf rules:

    That does not work for me. I do not have control over all the rules since I'm using nextjs. I could technically but the order of the rules isn't some public API. And even then the point about future rules still apply: I need to manually verify no rules conflicts whenever I update nextjs.

  14. alexander-akait commented on Mar 16, 2021

    @alexander-akait
    Member

    @sokra using oneOf is not very convenient in many cases, also some developers can't have access to webpack.config.js

  15. 5 remaining items

  16. sokra commented on Mar 16, 2021

    @sokra
    Member

    I think we should try to avoid webpack specific syntax in code, it will be problem in future...

    Yeah that why I only mentioned the other solutions first.

    But he is already using require.context as webpack-specific syntax and there is not official replacement for that and there probably won't be...

    If you want a solution without any webpack magic you can go with:

    1. Create a pre build script that collects all source code needed into a JSON file.
    2. Import that JSON file during the build.
  17. slorber commented on Apr 30, 2021

    @slorber

    I have a distinct but similar case where I feel it's complicated to migrate to the asset modules system.

    Docusaurus has a modular architecture with a plugin system.

    A Docusaurus image plugin should be able to "override" the default image asset module rule.

    It looks to me that before, the order mattered, and we just had to add the custom image loader at the beginning of the list rule to override the existing rule. So we have plugins that do:

    export default function docusaurusPlugin() {
      return {
        name: 'docusaurus-plugin-ideal-image',
        configureWebpack() {
          return {
            mergeStrategy: {
              'module.rules': 'prepend', // using webpack-merge prepend customization rule
            },
            module: {
              rules: [
                {
                  test: /\.(png|jpe?g|gif)$/i,
                  loader: "custom-image-loader",
                },
              ],
            },
          };
        },
      };
    }

    It seems that now, adding this rule at the beginning does not prevent the default asset loaders in Docusaurus core to be used, unless we use oneOf.

    I don't feel like using oneOf is very good in this case because it would break our existing plugin ecosystem that relies on append/prepend in rules, and expose more implementation details of the core Webpack config to plugins that want to customize it. Playing with resourceQuery and notResourceQuery is also not very convenient in our case, as plugin authors would have to potentially add notResourceQuery clauses.

    For Docusaurus, using oneOf could work, as we don't have a large plugin ecosystem it might affect only a few users, but I guess it could be more problematic for larger frameworks like Next.js or Gatsby.

    Apart that, I like this new asset modules system, more convenient that using inline loader syntax with a messy querystring

    Edit: here's a migration PR attempt: meta/docusaurus#4708

  18. webpack-bot commented on Oct 16, 2021

    @webpack-bot
    Contributor

    This issue had no activity for at least three months.

    It's subject to automatic issue closing if there is no activity in the next 15 days.

  19. added
    status: stale
    on Oct 16, 2021
  20. removed
    status: stale
    on Oct 30, 2021
  21. added
    status: stale
    on Feb 12, 2022
  22. removed
    status: stale
    on Feb 20, 2022
  23. sokra commented on Feb 20, 2022

    @sokra
    Member

    Don't use .default?

  24. Airkro commented on Apr 21, 2022

    @Airkro

    Is possible to support type as import.meta.webpackContext parameter?

  25. vankop commented on Apr 21, 2022

    @vankop
    Contributor

    Is possible to support type as import.meta.webpackContext parameter?

    there is no type in import.meta.webpackContext. we don't plan to support more options for require.context.

  26. vankop commented on Apr 21, 2022

    @vankop
    Contributor

    there is an answer on original issue. please create separate issues.

  27. ITsvetkoFF commented on Mar 22, 2023

    @ITsvetkoFF

    For those who are struggling with

        {
           test: /\.m?js$/,
           resourceQuery: { not: [/raw/] },
           use: [ ... ]
         },
    

    for a webpack config that you are not controlling completely (like in Storybook)

    there is another approach that I (in a desperate moment) was able to find in code search over github: source

    where this happens:

    config.module.rules.forEach(rule => {
        rule.resourceQuery = { not: [/raw/] };
      });
      config.module.rules.push(
        {
          resourceQuery: /raw/,
          type: 'asset/source',
        });
      return config;
    
  28. MichaelAllenWarner commented on Aug 7, 2024

    @MichaelAllenWarner

    btw. there is another way, which would work without touching any other part of the config:

          {
            test: /\.txt$/,
            type: "asset/source",
          },
    import source from "file.txt!=!./file.js";
    

    This treats content of file.js as it was written in file.txt.

    Not sure if this works with require.context, but you could try it with require.context("code.txt!=!./code", false, /\.js$/), but this might look a bit weird anyway.

    Otherwise you could also go with:

    import sources from "./all-code.js!";
    

    and generate code like that in the all-code.js loader:

    export { default as abc } from "code/abc.js.txt!=!./code/abc.js";
    export { default as def } from "code/def.js.txt!=!./code/def.js";
    // ...

    This is extremely ugly but worked for me. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    webpack-5

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions