Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

windicss-webpack-plugin

Package Overview
Dependencies
Maintainers
4
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

windicss-webpack-plugin - npm Package Compare versions

Comparing version 1.4.10 to 1.5.0

CHANGELOG.md

66

dist/loaders/pitcher.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.pitch = void 0;
const constants_1 = require("../constants");
const isTemplateLoader = (l) => /(\/|\\|@)transform-template/.test(l.path);
const postCSSLoader = (l) => /(\/|\\|@)postcss-loader/.test(l.path);
const cssLoader = (l) => /(\/|\\|@)css-loader/.test(l.path);
const isPitcherLoader = (l) => `${constants_1.NAME}:pitcher` === l.ident;
/*
* Move the position of the transform-template loader for Vue SFCs.
*
* We move it just after the PostCSS loader
*/
var _constants = require("../core/constants");
const isTemplateLoader = l => /(\/|\\|@)transform-template/.test(l.path);
const postCSSLoader = l => /(\/|\\|@)postcss-loader/.test(l.path);
const cssLoader = l => /(\/|\\|@)css-loader/.test(l.path);
const isPitcherLoader = l => `${_constants.NAME}:pitcher` === l.ident;
const pitch = function (remainingRequest) {
// remove the pitcher immediately
const pitcherLoaderIndex = this.loaders.findIndex(isPitcherLoader);
if (pitcherLoaderIndex !== -1)
this.loaders.splice(pitcherLoaderIndex, 1);
// make sure we're dealing with style-loader
if (!remainingRequest.includes('&type=style'))
return;
let newTemplateLoaderIndex = this.loaders.findIndex(postCSSLoader);
// just in-case they don't have post-css for whatever reason we also search for the css-loader
if (newTemplateLoaderIndex === -1)
newTemplateLoaderIndex = this.loaders.findIndex(cssLoader);
// we couldn't find either PostCSS loader or CSS loader so we bail out
if (newTemplateLoaderIndex === -1)
return;
// remove all instances of the template-loader
let templateLoaderIndex, templateLoader;
while ((templateLoaderIndex = this.loaders.findIndex(isTemplateLoader)) !== -1) {
templateLoader = this.loaders[templateLoaderIndex];
this.loaders.splice(templateLoaderIndex, 1);
}
// re-insert the template-loader in the right spot
if (templateLoader)
this.loaders.splice(newTemplateLoaderIndex + 1, 0, templateLoader);
const pitcherLoaderIndex = this.loaders.findIndex(isPitcherLoader);
if (pitcherLoaderIndex !== -1) this.loaders.splice(pitcherLoaderIndex, 1);
if (!remainingRequest.includes("&type=style")) return;
let newTemplateLoaderIndex = this.loaders.findIndex(postCSSLoader);
if (newTemplateLoaderIndex === -1) newTemplateLoaderIndex = this.loaders.findIndex(cssLoader);
if (newTemplateLoaderIndex === -1) return;
let templateLoaderIndex, templateLoader;
while ((templateLoaderIndex = this.loaders.findIndex(isTemplateLoader)) !== -1) {
templateLoader = this.loaders[templateLoaderIndex];
this.loaders.splice(templateLoaderIndex, 1);
}
if (templateLoader) this.loaders.splice(newTemplateLoaderIndex + 1, 0, templateLoader);
};
exports.pitch = pitch;
exports.pitch = pitch;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = __importDefault(require("../debug"));
Object.defineProperty(exports, "__esModule", {
value: true
});
module.exports = void 0;
var _debug = _interopRequireDefault(require("../core/debug"));
var _utils = require("../core/utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function TransformCss(source) {
if (!this._compiler)
return source;
this.cacheable(true);
const service = this._compiler.$windyCSSService;
if (!service)
return source;
let output = source;
try {
output = service.transformCSS(source, this.resource);
debug_1.default.loader('Transformed CSS', this.resource);
}
catch (e) {
this.emitWarning(`[Windi CSS] Failed to css for resource: ${this.resource}.`);
}
return output || source;
if (!this._compiler) return source;
this.cacheable(true);
const service = this._compiler.$windyCSSService;
if (!service) return source;
if (!(0, _utils.cssRequiresTransform)(source)) return source;
let output = source;
try {
output = service.transformCSS(source, this.resource);
_debug.default.loader("Transformed CSS", this.resource);
} catch (e) {
this.emitWarning(`[Windi CSS] Failed to css for resource: ${this.resource}.`);
}
return output || source;
}
exports.default = TransformCss;
var _default = TransformCss;
module.exports = _default;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = __importDefault(require("../debug"));
const compileTemplate = require('lodash/template');
const defaults = require('lodash/defaults');
const loaderUtils = require('loader-utils');
Object.defineProperty(exports, "__esModule", {
value: true
});
module.exports = void 0;
var _template = _interopRequireDefault(require("lodash/template"));
var _defaults = _interopRequireDefault(require("lodash/defaults"));
var _loaderUtils = _interopRequireDefault(require("loader-utils"));
var _debug = _interopRequireDefault(require("../core/debug"));
var _utils = require("../core/utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function TransformTemplate(source) {
if (!this._compiler)
return source;
this.cacheable(true);
const service = this._compiler.$windyCSSService;
if (!service)
return source;
/*
* Via the pitcher loader we can transfer post-interpreted CSS
*/
if (this.resource.indexOf('type=style') > 0)
return service.transformCSS(source, this.resource);
const hasHtmlWebpackPlugin = this.loaders.filter((loader) => {
// loader name as unresolved module
return (loader.loader && loader.loader.indexOf('html-webpack-plugin') > 0)
// resolved loader name as path
|| (loader.path && loader.path.indexOf('html-webpack-plugin') > 0);
}).length > 0;
if (hasHtmlWebpackPlugin) {
/*
* Because the html-webpack-plugin doesn't support multiple loaders, we need to replicate the behaviour of the plugin
* here, this is pretty hacky but haven't been able to find a solution. @todo find a better solution
*
* Source: html-webpack-plugin/lib/loader.js
*/
const options = this.query !== '' ? loaderUtils.parseQuery(this.query) : {};
const template = compileTemplate(source, defaults(options, { variable: 'data' }));
// Require !!lodash - using !! will disable all loaders (e.g. babel)
return `var _ = require(${loaderUtils.stringifyRequest(this, `!!${require.resolve('lodash')}`)});`
+ 'module.exports = function (templateParams) { with(templateParams) {'
// Execute the lodash template
+ `return (${template.source})();`
+ '}}';
}
let output = source;
try {
const templateWithTransformedCSS = source.replace(/<style(.*?)>(.*)<\/style>/gms, (match, meta, css) => {
// bail out, return the original match
if (meta.includes('sass') || meta.includes('stylus') || meta.includes('less')) {
debug_1.default.loader('Template has unsupported block, skipping resource', this.resource);
return match;
if (!this._compiler) return source;
this.cacheable(true);
const service = this._compiler.$windyCSSService;
if (!service) return source;
if (this.resource.indexOf("type=style") > 0) {
if (!(0, _utils.cssRequiresTransform)(source)) return source;
return service.transformCSS(source, this.resource);
}
const hasHtmlWebpackPlugin = this.loaders.filter(loader => {
return loader.loader && loader.loader.indexOf("html-webpack-plugin") > 0 || loader.path && loader.path.indexOf("html-webpack-plugin") > 0;
}).length > 0;
if (hasHtmlWebpackPlugin) {
const options = this.query !== "" ? _loaderUtils.default.parseQuery(this.query) : {};
const template = (0, _template.default)(source, (0, _defaults.default)(options, {
variable: "data"
}));
return `var _ = require(${_loaderUtils.default.stringifyRequest(this, `!!${require.resolve("lodash")}`)});module.exports = function (templateParams) { with(templateParams) {return (${template.source})();}}`;
}
let output = source;
try {
const templateWithTransformedCSS = source.replace(/<style(.*?)>(.*)<\/style>/gms, (match, meta, css) => {
if (meta.includes("sass") || meta.includes("stylus") || meta.includes("less")) {
_debug.default.loader("Template has unsupported block, skipping resource", this.resource);
return match;
}
if (!(0, _utils.cssRequiresTransform)(match)) return match;
if ((0, _utils.isJsx)(css)) {
let m, transformedCSS;
const jsxMatcher = /{`(.*)`}/gms;
while ((m = jsxMatcher.exec(css)) !== null) {
if (m.index === jsxMatcher.lastIndex) jsxMatcher.lastIndex++;
m.forEach((match2, groupIndex) => {
if (groupIndex === 1) {
transformedCSS = `<style${meta}>
{\`${service.transformCSS(match2, this.resource)}
\`}</style>`;
_debug.default.loader("jsx transformed", transformedCSS);
}
// for jsx styles we need to replace the contents of template strings
if (/{`(.*)`}/gms.test(css)) {
let m, transformedCSS;
const jsxMatcher = /{`(.*)`}/gms;
while ((m = jsxMatcher.exec(css)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === jsxMatcher.lastIndex)
jsxMatcher.lastIndex++;
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if (groupIndex === 1) {
transformedCSS = `<style${meta}>\n{\`${service.transformCSS(match, this.resource)}\n\`}</style>`;
debug_1.default.loader('jsx transformed', transformedCSS);
}
});
}
return transformedCSS !== null && transformedCSS !== void 0 ? transformedCSS : match;
}
return `<style${meta}>\n${service.transformCSS(css, this.resource)}\n</style>`;
});
debug_1.default.loader('Transformed template ', this.resource);
const transformed = service.transformGroups(templateWithTransformedCSS);
if (transformed)
output = transformed.code;
else
output = templateWithTransformedCSS;
}
catch (e) {
this.emitWarning(`[Windi CSS] Failed to transform groups and css for template: ${this.resource}.`);
}
return output;
});
}
return transformedCSS ?? match;
}
return `<style${meta}>
${service.transformCSS(css, this.resource)}
</style>`;
});
_debug.default.loader("Transformed template ", this.resource);
const transformed = service.transformGroups(templateWithTransformedCSS);
if (transformed) output = transformed.code;else output = templateWithTransformedCSS;
} catch (e) {
this.emitWarning(`[Windi CSS] Failed to transform groups and css for template: ${this.resource}.`);
}
return output;
}
exports.default = TransformTemplate;
var _default = TransformTemplate;
module.exports = _default;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importStar(require("fs"));
const plugin_utils_1 = require("@windicss/plugin-utils");
const constants_1 = require("../constants");
const debug_1 = __importDefault(require("../debug"));
module.exports = void 0;
var _fs = _interopRequireWildcard(require("fs"));
var _pluginUtils = require("@windicss/plugin-utils");
var _constants = require("../core/constants");
var _debug = _interopRequireDefault(require("../core/debug"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
async function VirtualModule(source) {
const callback = this.async();
if (!this._compiler) {
callback(null, source);
return;
const callback = this.async();
if (!this._compiler) {
callback(null, source);
return;
}
this.cacheable(false);
const service = this._compiler.$windyCSSService;
const match = this.resource.match(_constants.MODULE_ID_VIRTUAL_TEST);
if (!service || !match) {
const error = new Error(`Failed to match the resource "${this.resource}" to a WindiCSS virtual module.`);
this.emitError(error);
callback(error, source);
return;
}
const layer = match[1] || void 0;
const isBoot = source.indexOf("(boot)") > 0;
_debug.default.loader(`Generating "${this.resource}" using layer "${layer}${isBoot ? '" as boot ' : " as hmr"}`);
const generateCSS = async layer2 => {
try {
if (service.scanned && service.options.enableScan) service.options.enableScan = false;
const css = (await service.generateCSS(layer2)).replace("(boot)", "");
service.virtualModules.set(layer2 ?? "all", css);
callback(null, css);
} catch (e) {
const error = JSON.stringify(e, null, 2);
this.emitError(`[Windi CSS] Failed to generate CSS. Error: ${error}`);
callback(e, `${source}
/* Error: ${error}*/`);
}
this.cacheable(false);
const service = this._compiler.$windyCSSService;
const match = this.resource.match(constants_1.MODULE_ID_VIRTUAL_TEST);
if (!service || !match) {
const error = new Error(`Failed to match the resource "${this.resource}" to a WindiCSS virtual module.`);
this.emitError(error);
callback(error, source);
return;
}
const layer = match[1] || undefined;
const isBoot = source.indexOf('(boot)') > 0;
debug_1.default.loader(`Generating "${this.resource}" using layer "${layer}${isBoot ? '" as boot ' : ' as hmr'}`);
const generateCSS = async (layer) => {
};
if (isBoot) {
await generateCSS(layer);
return;
}
const dirtyFiles = Array.from(service.dirty);
if (dirtyFiles.length === 0) {
callback(null, source);
return;
}
if (service.dirty.has("all-modules")) {
const contents = await Promise.all([...(await service.getFiles())].filter(id => service.isDetectTarget(id)).map(async id => [await _fs.default.promises.readFile(id, "utf-8"), id]));
await Promise.all(contents.map(async ([content, id]) => {
if (service.isCssTransformTarget(id)) return service.transformCSS(content, id);else return service.extractFile(content, id, true);
}));
} else {
const configFileUpdated = dirtyFiles.filter(id => {
return _pluginUtils.defaultConfigureFiles.filter(config => {
return id.endsWith(config);
}).length > 0;
}).length > 0;
if (configFileUpdated) {
service.clearCache();
await service.init();
} else {
const contents = await Promise.all(dirtyFiles.map(id => {
return {
data: (0, _fs.readFileSync)(id, {
encoding: "utf-8"
}),
id
};
}));
for (const content of contents) {
try {
// avoid duplicate scanning on HMR
if (service.scanned && service.options.enableScan)
service.options.enableScan = false;
const css = (await service.generateCSS(layer)).replace('(boot)', '');
service.virtualModules.set(layer !== null && layer !== void 0 ? layer : 'all', css);
callback(null, css);
await service.extractFile(content.data, content.id, service.options.transformGroups);
} catch (e) {
this.emitWarning(`[Windi CSS] Failed to extract classes from resource: ${content.id}.`);
}
catch (e) {
const error = JSON.stringify(e, null, 2);
this.emitError(`[Windi CSS] Failed to generate CSS. Error: ${error}`);
callback(e, `${source}\n` + `/* Error: ${error}*/`);
}
};
if (isBoot) {
await generateCSS(layer);
return;
}
}
// Make sure we're hot
const dirtyFiles = Array.from(service.dirty);
if (dirtyFiles.length === 0) {
callback(null, source);
return;
}
// Need to do a complete re-scan, we got a null entry on the watcher so we know a file updated but don't know which one
if (service.dirty.has('all-modules')) {
const contents = await Promise.all([...(await service.getFiles())]
.filter(id => service.isDetectTarget(id))
.map(async (id) => [await fs_1.default.promises.readFile(id, 'utf-8'), id]));
await Promise.all(contents.map(async ([content, id]) => {
if (service.isCssTransformTarget(id))
return service.transformCSS(content, id);
else
return service.extractFile(content, id, true);
}));
}
else {
const configFileUpdated = dirtyFiles.filter((id) => {
return plugin_utils_1.defaultConfigureFiles.filter((config) => {
return id.endsWith(config);
}).length > 0;
}).length > 0;
// If it is a config update we init the service again
if (configFileUpdated) {
service.clearCache();
await service.init();
}
else {
// Get all of our dirty files and parse their content
const contents = await Promise.all(dirtyFiles.map((id) => {
return {
data: (0, fs_1.readFileSync)(id, { encoding: 'utf-8' }),
id,
};
}));
// Extract the content into windicss service
for (const content of contents) {
try {
await service.extractFile(content.data, content.id, service.options.transformGroups);
}
catch (e) {
this.emitWarning(`[Windi CSS] Failed to extract classes from resource: ${content.id}.`);
}
}
}
}
// Don't process the same files until they're dirty again
service.dirty.clear();
await generateCSS(layer);
}
service.dirty.clear();
await generateCSS(layer);
}
exports.default = VirtualModule;
var _default = VirtualModule;
module.exports = _default;

@@ -1,7 +0,30 @@

import { Compiler, Options } from './interfaces';
import webpack from 'webpack';
import { WindiPluginUtils, UserOptions } from '@windicss/plugin-utils';
declare type Compiler = webpack.Compiler & {
$windyCSSService?: WindiPluginUtils & {
dirty: Set<string>;
root: string;
virtualModules: Map<string, string>;
initException?: Error;
};
};
declare type WindiCSSWebpackPluginOptions = UserOptions & {
/**
* Reuse existing utils if exists
*/
utils?: WindiPluginUtils;
/**
* The path where the virtual module should be injected. By default this is the project root but for
* some projects (such as craco), specifying the directory is needed.
*/
virtualModulePath?: string;
};
declare class WindiCSSWebpackPlugin {
options: Options;
constructor(options?: Options);
options: WindiCSSWebpackPluginOptions;
constructor(options?: WindiCSSWebpackPluginOptions);
apply(compiler: Compiler): void;
}
export default WindiCSSWebpackPlugin;
export { WindiCSSWebpackPlugin as default };
{
"name": "windicss-webpack-plugin",
"version": "1.4.10",
"version": "1.5.0",
"license": "MIT",

@@ -9,2 +9,9 @@ "author": {

},
"exports": {
"import": "./dist/plugin.mjs",
"require": "./dist/plugin.cjs"
},
"main": "./dist/plugin.cjs",
"module": "./dist/plugin.mjs",
"types": "./dist/module.d.ts",
"homepage": "https://github.com/windicss/windicss-webpack-plugin",

@@ -19,5 +26,4 @@ "bugs": "https://github.com/windicss/windicss-webpack-plugin/issues",

],
"main": "dist/index.js",
"scripts": {
"build": "rm -rf dist && tsc && cp src/modules.d.ts dist",
"build": "unbuild",
"pretest": "npm run build",

@@ -56,3 +62,3 @@ "test": "set DEBUG=windicss* && jest --coverage",

"devDependencies": {
"@antfu/eslint-config": "^0.6.6",
"@antfu/eslint-config": "^0.10.0",
"@babel/preset-env": "^7.15.8",

@@ -64,4 +70,5 @@ "@babel/preset-react": "^7.14.5",

"@types/loader-utils": "^2.0.3",
"@types/lodash": "^4.14.176",
"@types/webpack": "^4.41.31",
"babel-loader": "^8.2.2",
"babel-loader": "^8.2.3",
"css-loader": "^5.2.7",

@@ -86,3 +93,4 @@ "dotenv-cli": "^4.0.0",

"ts-jest": "^26.5.6",
"typescript": "^4.4.3",
"typescript": "^4.4.4",
"unbuild": "^0.5.11",
"unionfs": "^4.4.0",

@@ -89,0 +97,0 @@ "vue-loader": "^15.9.8",

@@ -18,8 +18,6 @@ <h1 align='center'>windicss-webpack-plugin</h1>

- 🧩 On-demand CSS utilities (Compatible with Tailwind CSS v2)
- 📦 On-demand native elements style reseting
- 🔥 Hot module replacement (HMR)
- 🧩 On-demand CSS utilities (Compatible with Tailwind CSS v2) and preflights
- 🍃 Load configurations from `tailwind.config.js`
- 🤝 Framework-agnostic: Vue CLI, Nuxt, Next, UmiJS, etc!
- 📄 Use `@apply` / `@screen` directives in any file: Less, SCSS, SASS, PostCSS, Stylus
- 📄 Use [directives](https://windicss.org/features/directives.html) in any CSS (SCSS, LESS, etc) `@apply`, `@variants`, `@screen`, `@layer`, `theme()`,
- 🎳 Support Utility Groups - e.g. `bg-gray-200 hover:(bg-gray-100 text-red-300)`

@@ -26,0 +24,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc