首先咱们要知道 loader 插件是写在哪里的
打开webpack.config.js
文件, 在module.rules
中加入咱们的自定义 loader:
{ test: /.ts$/, use: [ { loader: path.resolve(__dirname,'./build/loader.js'), options: { foo: true, } } ] }
参数获取:css
const options = getOptions(this);
传入的参数校检:html
const schema = { type: 'object', properties: { test: { type: 'string' } } } as const validate(schema, options);
而咱们建立对应路径的 loader.ts 这里咱们使用 ts 来写 loader:
loader.ts:vue
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 代码:webpack
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, 若是有兴趣能够本身查阅git
像这样 咱们就能建立咱们本身的 loader, 在里面对咱们的源码进行不一样的操做, 像是 vue-loader 就是经过标签 分开三种(html,js,css) 系统的代码 再将其经过剩余 loader 里面
本文中写的 loader: https://github.com/Grewer/JsDemo/blob/master/webpackLoader/loader.tsgithub