>  기사  >  위챗 애플릿  >  WeChat 애플릿 변환기 로더 설계 및 구현

WeChat 애플릿 변환기 로더 설계 및 구현

coldplay.xixi
coldplay.xixi앞으로
2020-11-19 17:36:123747검색

미니 프로그램 개발 튜토리얼 칼럼에서는 로더의 설계와 구현을 소개합니다.

WeChat 애플릿 변환기 로더 설계 및 구현

구성 파일

의 로더 구성은 구성 파일에 따른 규칙을 일치시켜 해당 로더를 실행할 수 있습니다.

// analyze.config.js
// 引入loader
const jsLoader = require('./lib/jsLoader')
const jsonLoader = require('./lib/jsonLoader')
const cssLoader = require('./lib/cssLoader')
const htmlLoader = require('./lib/htmlLoader')
const signLoader = require('./lib/signLoader')
const config = {
    entry: './',
    output: {
        name: 'dist',
        src: './'
    },
    module: [
        {
            test: /\.js$/,
            loader: [signLoader, jsLoader],
        },
        {
            test: /\.wxss$/,
            loader: [cssLoader],
            outputPath: (outputPath) => outputPath.replace('.wxss', '.acss')
        },
        {
            test: /\.wxml$/,
            loader: [htmlLoader],
            outputPath: (outputPath) => outputPath.replace('.wxml', '.axml')
        },
        {
            test: /\.json$/,
            loader: [jsonLoader],
        },
    ]
}
module.exports = config

특정 로더 구현
jsLoader를 예로 들어 소스 코드를 매개변수로 받고 컴파일 후 얻은 새 소스 코드를 반환합니다.

// 前几篇中封装的js转换器
const JsParser = require('./JsParser')
function loader(source) {
    
    const jsParser = new JsParser()
    let ast = jsParser.parse(source)
    ast = jsParser.astConverter(ast)
    return jsParser.astToCode(ast)
}
module.exports = loader

다른 파일 선택은 로더에 해당합니다

// 重写Analyze函数中的analyzeFileToLoard文件分析部分
function Analyze(filePath, outputPath){
    if (fs.statSync(filePath).isDirectory()) {
        const files = fs.readdirSync(filePath)
        files.forEach(file => {
            const currentFilePath = filePath+'/'+file
            const currentOutputPath = outputPath+'/'+file
            if(fs.statSync(currentFilePath).isDirectory()) {
                fs.mkdirSync(currentOutputPath)
                Analyze(currentFilePath, currentOutputPath)
            } else analyzeFileToLoard(currentFilePath, currentOutputPath)
        })
    } else analyzeFileToLoard(filePath, outputPath)
}
function analyzeFileToLoard(inputPath, outputPath) {
    let source = readFile(inputPath) // 读取源码
    const loaders = config.module
    loaders.forEach(loader => { // 遍历配置文件,看是否有匹配文件的loader规则
        if (loader.test.test(inputPath)) {
            // 使用loader
            source = useLoader(source, loader.loader, outputPath)
            // 输出路径处理函数
            if (loader.outputPath) outputPath = loader.outputPath(outputPath)
        }
    })
    writeFile(outputAppPath(outputPath), source) // 将处理过后的源码写入文件
}

loader 필터링 및 실행

로더 실행은 오른쪽에서 왼쪽으로 역순입니다. 여기서는 먼저 동기식 로더를 사용하여 논의합니다.
로더가 실행되기 전에 피치 단계가 있습니다. 피치의 명명 방법이 특별히 적합하지 않다고 생각합니다. 먼저 로더에서 피치 메소드를 순차적으로 실행합니다. 피치에 반환 값이 있으면 로더 이전에 실행된 로더는 더 이상 실행되지 않습니다.

function useLoader(source, loaders = []) {
    // 执行loader存储列表
    const loaderList = []
    // 递归去筛选需要执行的loader
    function loaderFilter(loaders) {
        const [firstLoader, ...ortherLoader] = loaders
        if (loaders.length === 0) return
        // 执行pitch,并将剩余的loader传入作为参数
        if (firstLoader.pitch && firstLoader.pitch(ortherLoader)) return ortherLoader
        else {
            // 将可用loader加入待执行列表
            loaderList.push(firstLoader)
            // 剩余loader作为参数 递归调用
            loaderFilter(ortherLoader)
        }
    }
    // 大概,暂时用不到。。。
    const remainLoader = loaderFilter(loaders)
    // 同步loader逆序执行
    function runLoader(source, loaderList) {
        const loader = loaderList.pop()
        let newSource = loader(source)
        if (loaderList.length > 0) return runLoader(newSource, loaderList)
        else return newSource
    }
    source = runLoader(source, loaderList)
    return source
}

실험
signLoader를 작성하여 우리가 생각한 대로 로더가 역순으로 실행될 수 있는지 확인하세요.

function loader(source) {
let sign = `/**
* @Author: LY
*/
`
    source = sign + source
    return source
}
module.exports = loader

결과:

이 간단한 로더 부분은 완료되었지만 이렇게 작성하면 일부 동기 로더만 실행할 수 있습니다. 로더는 쓰기 전에 실행이 완료될 때까지 기다릴 수 없습니다.

WeChat 애플릿 변환기 로더 설계 및 구현

관련 학습 권장 사항: Mini 프로그램 개발 튜토리얼

위 내용은 WeChat 애플릿 변환기 로더 설계 및 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.im에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제