webpack loader 實現

位置

首先咱們要知道 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

相關文章
相關標籤/搜索