3

I'm trying to write a Webpack loader that whenever I import a specific fixed string "Hello" like below, it runs my loader at compile time and return a non-cacheable string.

import x from 'Hello';

console.log(x)

The thing here is that "Hello" is not a file.

I was trying to do this by introducing my loader in the Webpack Config in module.rules by having my loader's test prop as "Hello" but it didn't work.

// webpack.config.js
{
  ...
  module: { 
    rules: [
      {
        test: /Hello/,
        use: [
          {
            loader: path.resolve('./my-custom-loader.js'),
            options: {
              /* ... */
            },
          },
        ],
      },
      ...
    ],
    ...
  }
}

Is this even possible in Webpack?

Shnd
  • 1,846
  • 19
  • 35
  • I found this but it didn't work for me: https://github.com/webpack/webpack/issues/3633 – Shnd Aug 02 '21 at 00:02

1 Answers1

-3

// Assuming that your customer loaders are in the loaders directory

my-customer-loader.js

./loaders/my-customer-loader.js

// Your customer loader my-customer-loader.js

module.exports = function(source){
    console.log(source)
    results = source + 'change source'
    return source
}

// webpack.config.js

{
    ....
    
    resolveLoader: {
        // webpack by default looks for loaders in node_modules so your must declare where you loader is located
        module: ['node_modules', path.resolve(__dirname, 'loaders')]
    },
    Module: {
        rules: [
            test: /\.js$/,
            use: 'my-customer-loader'
        ]
    }
    ......
}
  • Sorry Moeketsi but your answer is irrelevant to the question. The question is not about importing '.js' files. – Shnd Aug 01 '21 at 03:03