2

I'm building a documentation site in which I want to display demo code snippets.

With the styles, it was really straight forward, as my app is only including the main.scss, so I'm processing that file with all the necessary loaders to compile it, and any other scss file is loaded using the raw-loader to get the file as plain text.

The problem I'm having is at the moment of doing the same with my components. Unlike my styles, I need to include my components both when I want to render them using babel-loader, but I also want to import them as plain text for the demo showcase.

At first I thought of compromising using an inline loader at the require level

const componentCode = require('raw-loader!./path/to/component');

The problem with this approach is that by the time I try to do this import, the file has already been ran through babel-loader so I get the compiled version of the file instead of the original. I tried passing ?enforce=pre as a query parameter to the raw-loader inline, but this had no effect.

I was wondering if there is a way of defining a rule to override an import/require statement.

According to the webpack documentation

It's possible to overwrite any loaders in the configuration by prefixing the entire rule with !.

However, I can not find any examples of this. I tried the following, which compiled but crashed right after the first ! prefixed require without any errors

webpack.coonfig.js

{
    test: /\.(js|jsx)$/,
    exclude: [/node_modules/],
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['env', 'react'],
        },
      },
    ],
  },
  {
    test: /!*\.(js|jsx)$/,
    enforce: "pre",
    use: [
      {
        loader: 'raw-loader',
      },
    ],
  },

file.jsx

  const componentCode = require('raw-loader!./path/to/component');

I also thought about reading the file using the fs but not sure if this will work. In the end the code will be compiled in its entirety by webpack and only the bundle will be published. Would this be the right approach?

Marcos Mellado
  • 125
  • 2
  • 11

1 Answers1

2

Found my answer at Webpack - ignore loaders in require()?, Basically I need !! before the require to ignore the pre loaders and apply mine

Marcos Mellado
  • 125
  • 2
  • 11