Answer the question
In order to leave comments, you need to log in
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);
};
require(`emit-file-loader?{output:"somefile.css"}!../src/someFileExample.txt`)
output:"somefile.css"
and it receives an argument from execution ../src/someFileExample.txt
require("emit-file-loader")({output:"somefile.css})("someTextToFileHere");
loaderUtils.getOptions(this)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question