条件编译Loader HandsomeHan 2021-09-02 JavaScript webpack Loader12345678910var loaderUtils = require('loader-utils')var reg = /(?:\/\*|<!--)\s*#ifdef\s*(\w+)(?:\s*(?:\*\/|-->))?([\s\S]+?)(?:(?:\/\*|<!--)\s*)?#endif\s*\1\s*(?:\*\/|-->)/gmodule.exports = function (source) { var options = loaderUtils.getOptions(this) return source.replace(reg, function (match, $1, $2) { return options[$1] ? $2 : '' })} config123456789101112131415chainWebpack: config => { config.resolveLoader.alias.set('compile-loader', path.resolve(__dirname, './config/conditional-compile-loader.js')) config.module .rule('vue') .use('compile-loader') .loader('compile-loader') .tap(() => { return { H5: true, APP: true, APPLET: true } }) .end() } usage123456789101112131415161718192021222324252627282930<template><!-- #ifdef H5 --><div class="public">这是H5环境</div><!-- #endif H5 --><!-- #ifdef APP --><div class="public">我是APP环境</div><!-- #endif APP --><!-- #ifdef DK --><div class="public">我是钉钉环境</div><!-- #endif DK --><!-- #ifdef APPLET --><div class="public">我是小程序环境</div><!-- #endif APPLET --></template><scirpt>/* #ifdef H5 */console.log(123);/* #endif H5 *//* #ifdef APP */console.log(456);/* #endif APP *//* #ifdef DK */console.log("dingtalk");/* #endif DK */</script>