webpack 中的 loader 的作用是什么
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 74
Author 回答者: wang120140
哎 lodaer 的作用就是处理单个文件的 跳到这啥都没有
Author 回答者: Linya-IronMan
webpack 是基于node的,只能处理 JS 和 JSON 文件,loader 的作用是用来处理其他类型的文件(less\vue…等)
可以将 less 转成 css 文件,将 jsx 处理成 JS 文件,将其他版本的ES处理成浏览器能识别的ES版本
Author 回答者: shfshanyue
loader 用以对某个文件进行 import 或者 require,在此过程中可能会涉及到解析与编译,如 js 通过 babel 进行编译。
以下是 url-loader 的源码,用以转化为 Base64 URL 的一个 loader,从中可以看出它把源代码 content 转化为被 webpack 支持的模块 module.exports = ***
function getEncodedData(generator, mimetype, encoding, content, resourcePath) {
if (generator) {
return generator(content, mimetype, encoding, resourcePath);
}
return `data:${mimetype}${encoding ? `;${encoding}` : ""},${content.toString(
// eslint-disable-next-line no-undefined
encoding || undefined,
)}`;
}
export default function loader(content) {
// Loader Options
const options = getOptions(this) || {};
validate(schema, options, {
name: "URL Loader",
baseDataPath: "options",
});
if (shouldTransform(options.limit, content.length)) {
const { resourcePath } = this;
const mimetype = getMimetype(options.mimetype, resourcePath);
const encoding = getEncoding(options.encoding);
if (typeof content === "string") {
// eslint-disable-next-line no-param-reassign
content = Buffer.from(content);
}
const encodedData = getEncodedData(
options.generator,
mimetype,
encoding,
content,
resourcePath,
);
const esModule =
typeof options.esModule !== "undefined" ? options.esModule : true;
return `${
esModule ? "export default" : "module.exports ="
} ${JSON.stringify(encodedData)}`;
}
// 忽略
}
// Loader Mode
export const raw = true;