地位

首先咱们要晓得 loader 插件是写在哪里的
关上 webpack.config.js 文件, 在 module.rules 中退出咱们的自定义 loader:
{    test: /.ts$/,    use: [             {                 loader: path.resolve(__dirname,'./build/loader.js'),                 options: { foo: true, }             }         ]}

参数获取:

const options = getOptions(this);

传入的参数校检:

const schema = {    type: 'object',    properties: { test: { type: 'string' } }} as constvalidate(schema, options);

而咱们创立对应门路的 loader.ts 这里咱们应用 ts 来写 loader:
loader.ts:

import {getOptions} from 'loader-utils';import {validate} from 'schema-utils';const schema = { type: 'object', properties: { test: { type: 'string' } }} as const// 用来验证参数的工具export default function (source) { //  通过工具函数 getOptions 来获取参数 const options = getOptions(this);     // 应用工具参数来验证, 如果不通过验证则抛出 Error     validate(schema, options);     // 打印代码    console.log('source', source)     // 在这里咱们能够对代码进行一系列的操作 // 如果咱们要替换一些不想要的数据:       const _source = source.replace(/alert(1)/, `console.log('grewer')`)     console.log('_source', _source)     return _source;};

当初应用 typescript 的 API 来解析 ts 代码:

 const compiler = typescript  let result = compiler.transpileModule(source, { compilerOptions: { module: typescript.ModuleKind.CommonJS } })  console.log(result.outputText)  return result.outputText;

对于 transpileModule 这个 API 须要查看文档:
原文档:https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
翻译的中文文档: https://zhuanlan.zhihu.com/p/141410800
typescript 具备很多咱们不常常应用的 api, 如果有趣味能够本人查阅

结语

像这样 咱们就能创立咱们本人的 loader, 在外面对咱们的源码进行不同的操作, 像是 vue-loader 就是通过标签 离开三种(html,js,css) 零碎的代码 再将其通过残余 loader 外面
本文中写的 loader: https://github.com/Grewer/JsDemo/blob/master/webpackLoader/loader.ts