weapp-tailwindcss
Version:
把 tailwindcss 原子化样式思想,带给小程序开发者们! bring tailwindcss to miniprogram developers!
393 lines (360 loc) • 17.3 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunkQZJTOS3Ujs = require('./chunk-QZJTOS3U.js');
var _chunkORSWL3MIjs = require('./chunk-ORSWL3MI.js');
var _chunkLTJQUORKjs = require('./chunk-LTJQUORK.js');
var _chunkIGTIMGCPjs = require('./chunk-IGTIMGCP.js');
var _chunkA2OSQ5CVjs = require('./chunk-A2OSQ5CV.js');
require('./chunk-PT4IJT3Q.js');
require('./chunk-6R4BK6D6.js');
var _chunkFMBPNII7js = require('./chunk-FMBPNII7.js');
require('./chunk-MB4BR57E.js');
// src/bundlers/webpack/BaseUnifiedPlugin/v4.ts
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _webpacksources = require('webpack-sources');
var debug = _chunkA2OSQ5CVjs.createDebug.call(void 0, );
var weappTailwindcssPackageDir = _chunkORSWL3MIjs.resolvePackageDir.call(void 0, "weapp-tailwindcss");
var UnifiedWebpackPluginV4 = class {
constructor(options = {}) {
this.options = _chunkA2OSQ5CVjs.getCompilerContext.call(void 0, options);
this.appType = this.options.appType;
}
apply(compiler) {
compiler.options = compiler.options || {};
const {
mainCssChunkMatcher,
disabled,
onLoad,
onUpdate,
onEnd,
onStart,
styleHandler,
templateHandler,
jsHandler,
runtimeLoaderPath,
runtimeCssImportRewriteLoaderPath,
cache,
twPatcher: initialTwPatcher,
refreshTailwindcssPatcher
} = this.options;
const disabledOptions = _chunkORSWL3MIjs.resolveDisabledOptions.call(void 0, disabled);
const isTailwindcssV4 = (_nullishCoalesce(initialTwPatcher.majorVersion, () => ( 0))) >= 4;
const shouldRewriteCssImports = isTailwindcssV4 && this.options.rewriteCssImports !== false && !disabledOptions.rewriteCssImports;
const isMpxApp = _chunkQZJTOS3Ujs.isMpx.call(void 0, this.appType);
if (shouldRewriteCssImports) {
_chunkQZJTOS3Ujs.applyTailwindcssCssImportRewrite.call(void 0, compiler, {
pkgDir: weappTailwindcssPackageDir,
enabled: true,
appType: this.appType
});
_chunkQZJTOS3Ujs.setupMpxTailwindcssRedirect.call(void 0, weappTailwindcssPackageDir, isMpxApp);
}
if (disabledOptions.plugin) {
return;
}
const patchRecorderState = _chunkIGTIMGCPjs.setupPatchRecorder.call(void 0, initialTwPatcher, this.options.tailwindcssBasedir, {
source: "runtime",
cwd: _nullishCoalesce(this.options.tailwindcssBasedir, () => ( _process2.default.cwd()))
});
const runtimeState = {
twPatcher: initialTwPatcher,
patchPromise: patchRecorderState.patchPromise,
refreshTailwindcssPatcher,
onPatchCompleted: patchRecorderState.onPatchCompleted
};
const refreshRuntimeState = async (force) => {
await _chunkA2OSQ5CVjs.refreshTailwindRuntimeState.call(void 0, runtimeState, force);
};
async function getClassSetInLoader() {
await refreshRuntimeState(true);
await runtimeState.patchPromise;
await _chunkA2OSQ5CVjs.collectRuntimeClassSet.call(void 0, runtimeState.twPatcher, { force: true, skipRefresh: true });
}
const runtimeClassSetLoader = _nullishCoalesce(runtimeLoaderPath, () => ( _path2.default.resolve(__dirname, "./weapp-tw-runtime-classset-loader.js")));
const runtimeCssImportRewriteLoader = shouldRewriteCssImports ? _nullishCoalesce(runtimeCssImportRewriteLoaderPath, () => ( _path2.default.resolve(__dirname, "./weapp-tw-css-import-rewrite-loader.js"))) : void 0;
const runtimeClassSetLoaderExists = _fs2.default.existsSync(runtimeClassSetLoader);
const runtimeCssImportRewriteLoaderExists = runtimeCssImportRewriteLoader ? _fs2.default.existsSync(runtimeCssImportRewriteLoader) : false;
const runtimeLoaderRewriteOptions = shouldRewriteCssImports ? {
pkgDir: weappTailwindcssPackageDir,
appType: this.appType
} : void 0;
const classSetLoaderOptions = {
getClassSet: getClassSetInLoader
};
const { findRewriteAnchor, findClassSetAnchor } = _chunkQZJTOS3Ujs.createLoaderAnchorFinders.call(void 0, this.appType);
const cssImportRewriteLoaderOptions = runtimeLoaderRewriteOptions ? {
rewriteCssImports: runtimeLoaderRewriteOptions
} : void 0;
onLoad();
if (shouldRewriteCssImports && isMpxApp) {
_chunkQZJTOS3Ujs.ensureMpxTailwindcssAliases.call(void 0, compiler, weappTailwindcssPackageDir);
}
if (runtimeCssImportRewriteLoader && shouldRewriteCssImports && cssImportRewriteLoaderOptions && isMpxApp) {
_chunkQZJTOS3Ujs.injectMpxCssRewritePreRules.call(void 0, compiler, runtimeCssImportRewriteLoader, cssImportRewriteLoaderOptions);
}
const createRuntimeClassSetLoaderEntry = () => ({
loader: runtimeClassSetLoader,
options: classSetLoaderOptions,
ident: null,
type: null
});
const createCssImportRewriteLoaderEntry = () => {
if (!runtimeCssImportRewriteLoader) {
return null;
}
return {
loader: runtimeCssImportRewriteLoader,
options: cssImportRewriteLoaderOptions,
ident: null,
type: null
};
};
compiler.hooks.compilation.tap(_chunkA2OSQ5CVjs.pluginName, (compilation) => {
compilation.hooks.normalModuleLoader.tap(_chunkA2OSQ5CVjs.pluginName, (_loaderContext, module) => {
const hasRuntimeLoader = runtimeClassSetLoaderExists || runtimeCssImportRewriteLoaderExists;
if (!hasRuntimeLoader) {
return;
}
if (shouldRewriteCssImports && _chunkQZJTOS3Ujs.isMpx.call(void 0, this.appType) && typeof _loaderContext.resolve === "function") {
_chunkQZJTOS3Ujs.patchMpxLoaderResolve.call(void 0, _loaderContext, weappTailwindcssPackageDir, true);
}
const loaderEntries = module.loaders || [];
let rewriteAnchorIdx = findRewriteAnchor(loaderEntries);
const classSetAnchorIdx = findClassSetAnchor(loaderEntries);
const isCssModule = _chunkQZJTOS3Ujs.isCssLikeModuleResource.call(void 0, module.resource, this.options.cssMatcher, this.appType);
if (_process2.default.env.WEAPP_TW_LOADER_DEBUG && isCssModule) {
debug("loader hook css module: %s loaders=%o anchors=%o", module.resource, loaderEntries.map((x) => x.loader), { rewriteAnchorIdx, classSetAnchorIdx });
}
if (_process2.default.env.WEAPP_TW_LOADER_DEBUG && typeof module.resource === "string" && module.resource.includes("app.css")) {
debug("app.css module loaders=%o anchors=%o", loaderEntries.map((x) => x.loader), { rewriteAnchorIdx, classSetAnchorIdx });
} else if (_process2.default.env.WEAPP_TW_LOADER_DEBUG && typeof module.resource === "string" && module.resource.endsWith(".css")) {
debug("css module seen: %s loaders=%o anchors=%o", module.resource, loaderEntries.map((x) => x.loader), { rewriteAnchorIdx, classSetAnchorIdx });
}
if (rewriteAnchorIdx === -1 && classSetAnchorIdx === -1 && !isCssModule) {
return;
}
const anchorlessInsert = (entry, position) => {
if (position === "after") {
loaderEntries.push(entry);
} else {
loaderEntries.unshift(entry);
}
};
if (runtimeLoaderRewriteOptions && runtimeCssImportRewriteLoaderExists && cssImportRewriteLoaderOptions && runtimeCssImportRewriteLoader) {
const existingIndex = loaderEntries.findIndex(
(entry) => _optionalChain([entry, 'access', _ => _.loader, 'optionalAccess', _2 => _2.includes, 'optionalCall', _3 => _3(runtimeCssImportRewriteLoader)])
);
const rewriteEntry = existingIndex !== -1 ? loaderEntries.splice(existingIndex, 1)[0] : createCssImportRewriteLoaderEntry();
if (rewriteEntry) {
const anchorIndex = findRewriteAnchor(loaderEntries);
if (anchorIndex === -1) {
anchorlessInsert(rewriteEntry, "after");
} else {
loaderEntries.splice(anchorIndex + 1, 0, rewriteEntry);
}
rewriteAnchorIdx = findRewriteAnchor(loaderEntries);
}
}
if (runtimeClassSetLoaderExists && !_chunkQZJTOS3Ujs.hasLoaderEntry.call(void 0, loaderEntries, runtimeClassSetLoader)) {
const anchorIndex = findClassSetAnchor(loaderEntries);
if (anchorIndex === -1) {
anchorlessInsert(createRuntimeClassSetLoaderEntry(), "before");
} else {
const insertIndex = anchorIndex === -1 ? rewriteAnchorIdx : anchorIndex;
loaderEntries.splice(insertIndex, 0, createRuntimeClassSetLoaderEntry());
}
}
});
});
compiler.hooks.emit.tapPromise(_chunkA2OSQ5CVjs.pluginName, async (compilation) => {
await runtimeState.patchPromise;
onStart();
debug("start");
for (const chunk of compilation.chunks) {
if (chunk.id && chunk.hash) {
cache.calcHashValueChanged(chunk.id, chunk.hash);
}
}
const assets = compilation.assets;
const entries = Object.entries(assets);
const outputDir = _optionalChain([compiler, 'access', _4 => _4.options, 'optionalAccess', _5 => _5.output, 'optionalAccess', _6 => _6.path]) ? _path2.default.resolve(compiler.options.output.path) : _process2.default.cwd();
const jsAssets = /* @__PURE__ */ new Map();
for (const [file] of entries) {
if (this.options.jsMatcher(file) || this.options.wxsMatcher(file)) {
const absolute = _chunkORSWL3MIjs.toAbsoluteOutputPath.call(void 0, file, outputDir);
jsAssets.set(absolute, file);
}
}
const moduleGraphOptions = {
resolve(specifier, importer) {
return _chunkORSWL3MIjs.resolveOutputSpecifier.call(void 0, specifier, importer, outputDir, (candidate) => jsAssets.has(candidate));
},
load: (id) => {
const assetName = jsAssets.get(id);
if (!assetName) {
return void 0;
}
const assetSource = compilation.assets[assetName];
if (!assetSource) {
return void 0;
}
const source = assetSource.source();
return typeof source === "string" ? source : source.toString();
},
filter(id) {
return jsAssets.has(id);
}
};
const applyLinkedResults = (linked) => {
if (!linked) {
return;
}
for (const [id, { code }] of Object.entries(linked)) {
const assetName = jsAssets.get(id);
if (!assetName) {
continue;
}
const assetSource = compilation.assets[assetName];
if (!assetSource) {
continue;
}
const previousSource = assetSource.source();
const previous = typeof previousSource === "string" ? previousSource : previousSource.toString();
if (previous === code) {
continue;
}
const source = new (0, _webpacksources.ConcatSource)(code);
compilation.updateAsset(assetName, source);
onUpdate(assetName, previous, code);
debug("js linked handle: %s", assetName);
}
};
const groupedEntries = _chunkFMBPNII7js.getGroupedEntries.call(void 0, entries, this.options);
await refreshRuntimeState(true);
await runtimeState.patchPromise;
const runtimeSet = await _chunkA2OSQ5CVjs.collectRuntimeClassSet.call(void 0, runtimeState.twPatcher, { force: true, skipRefresh: true });
debug("get runtimeSet, class count: %d", runtimeSet.size);
const tasks = [];
if (Array.isArray(groupedEntries.html)) {
for (const element of groupedEntries.html) {
const [file, originalSource] = element;
const rawSource = originalSource.source().toString();
const cacheKey = file;
tasks.push(
_chunkLTJQUORKjs.processCachedTask.call(void 0, {
cache,
cacheKey,
rawSource,
applyResult(source) {
compilation.updateAsset(file, source);
},
onCacheHit() {
debug("html cache hit: %s", file);
},
transform: async () => {
const wxml = await templateHandler(rawSource, {
runtimeSet
});
const source = new (0, _webpacksources.ConcatSource)(wxml);
onUpdate(file, rawSource, wxml);
debug("html handle: %s", file);
return {
result: source
};
}
})
);
}
}
const jsTaskFactories = [];
if (Array.isArray(groupedEntries.js)) {
for (const [file] of groupedEntries.js) {
const cacheKey = _chunkQZJTOS3Ujs.getCacheKey.call(void 0, file);
const assetSource = compilation.assets[file];
if (!assetSource) {
continue;
}
const initialValue = assetSource.source();
const initialRawSource = typeof initialValue === "string" ? initialValue : initialValue.toString();
const absoluteFile = _chunkORSWL3MIjs.toAbsoluteOutputPath.call(void 0, file, outputDir);
jsTaskFactories.push(async () => {
await _chunkLTJQUORKjs.processCachedTask.call(void 0, {
cache,
cacheKey,
rawSource: initialRawSource,
applyResult(source) {
compilation.updateAsset(file, source);
},
onCacheHit() {
debug("js cache hit: %s", file);
},
transform: async () => {
const currentAsset = compilation.assets[file];
const currentValue = _optionalChain([currentAsset, 'optionalAccess', _7 => _7.source, 'call', _8 => _8()]);
const currentSource = typeof currentValue === "string" ? currentValue : _nullishCoalesce(_optionalChain([currentValue, 'optionalAccess', _9 => _9.toString, 'call', _10 => _10()]), () => ( ""));
const { code, linked } = await jsHandler(currentSource, runtimeSet, {
filename: absoluteFile,
moduleGraph: moduleGraphOptions,
babelParserOptions: {
sourceFilename: absoluteFile
}
});
const source = new (0, _webpacksources.ConcatSource)(code);
onUpdate(file, currentSource, code);
debug("js handle: %s", file);
applyLinkedResults(linked);
return {
result: source
};
}
});
});
}
}
if (Array.isArray(groupedEntries.css)) {
for (const element of groupedEntries.css) {
const [file, originalSource] = element;
const rawSource = originalSource.source().toString();
const cacheKey = file;
tasks.push(
_chunkLTJQUORKjs.processCachedTask.call(void 0, {
cache,
cacheKey,
rawSource,
applyResult(source) {
compilation.updateAsset(file, source);
},
onCacheHit() {
debug("css cache hit: %s", file);
},
transform: async () => {
await runtimeState.patchPromise;
const { css } = await styleHandler(rawSource, {
isMainChunk: mainCssChunkMatcher(file, this.appType),
postcssOptions: {
options: {
from: file
}
},
majorVersion: runtimeState.twPatcher.majorVersion
});
const source = new (0, _webpacksources.ConcatSource)(css);
onUpdate(file, rawSource, css);
debug("css handle: %s", file);
return {
result: source
};
}
})
);
}
}
_chunkORSWL3MIjs.pushConcurrentTaskFactories.call(void 0, tasks, jsTaskFactories);
await Promise.all(tasks);
debug("end");
onEnd();
});
}
};
exports.UnifiedWebpackPluginV4 = UnifiedWebpackPluginV4; exports.weappTailwindcssPackageDir = weappTailwindcssPackageDir;