U
U
Undefined2021-12-24 00:13:08
webpack
Undefined, 2021-12-24 00:13:08

How to write a simple webpack loader?

Hello, trying to figure out the device of loaders, I'm wondering how the parameters for the loader are passed?
For example, a simple loader https://github.com/mortenson/emit-file-loader#readme
whose code

const loaderUtils = require('loader-utils');
module.exports = function loader(content, map, meta) {
  const options = loaderUtils.getOptions(this);
  if (options.output) {
    const name = loaderUtils.interpolateName(this, options.output, options);
    this.emitFile(name, content);
  }
  this.callback(null, content, map, meta);
};

You can use it
require(`emit-file-loader?{output:"somefile.css"}!../src/someFileExample.txt`)

Where do I pass parameters to the loader output:"somefile.css"and it receives an argument from execution ../src/someFileExample.txt
How to pass an argument and parameters using a function inside js, for example
require("emit-file-loader")({output:"somefile.css})("someTextToFileHere");

That is, I need to pass the value toloaderUtils.getOptions(this)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-12-24
@Undefined

The first thing to understand here is that the loader works at compile-time , and your js code where require - at run-time .
The loader receives the source text of the file (or the text issued by the previous loader) as input and outputs its own text. The last loader (it is the first in the webpack loader chain) should produce valid js.
Of course, your loader can generate a function in the output file, but it will not be able to affect the compilation process much.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question