Is it possible in Webpack to run my custom Loader whenever I import a fixed string and not a file?

Viewed 292

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?

1 Answers

// 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'
        ]
    }
    ......
}
Related