diff --git a/.eslintrc b/.eslintrc index da86310..77ef953 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,9 +2,6 @@ "extends": [ "fe", "fe/ts", - "plugin:jsx-advanced/recommended" - ], - "rules": { - "@typescript-eslint/no-duplicate-imports": "off" - } + "fe/react" + ] } \ No newline at end of file diff --git a/.gitignore b/.gitignore index aec42b3..a41e4e1 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,5 @@ typings/ # TernJS port file .tern-port + +examples/*/dist \ No newline at end of file diff --git a/.husky/_/.gitignore b/.husky/_/.gitignore new file mode 100644 index 0000000..f59ec20 --- /dev/null +++ b/.husky/_/.gitignore @@ -0,0 +1 @@ +* \ No newline at end of file diff --git a/.husky/_/husky.sh b/.husky/_/husky.sh new file mode 100644 index 0000000..cec959a --- /dev/null +++ b/.husky/_/husky.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env sh +if [ -z "$husky_skip_init" ]; then + debug () { + if [ "$HUSKY_DEBUG" = "1" ]; then + echo "husky (debug) - $1" + fi + } + + readonly hook_name="$(basename -- "$0")" + debug "starting $hook_name..." + + if [ "$HUSKY" = "0" ]; then + debug "HUSKY env variable is set to 0, skipping hook" + exit 0 + fi + + if [ -f ~/.huskyrc ]; then + debug "sourcing ~/.huskyrc" + . ~/.huskyrc + fi + + readonly husky_skip_init=1 + export husky_skip_init + sh -e "$0" "$@" + exitCode="$?" + + if [ $exitCode != 0 ]; then + echo "husky - $hook_name hook exited with code $exitCode (error)" + fi + + if [ $exitCode = 127 ]; then + echo "husky - command not found in PATH=$PATH" + fi + + exit $exitCode +fi diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 0000000..e417c1c --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx --no-install -- commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000..fc7c89d --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx --no-install -- lint-staged diff --git a/.lintstagedrc b/.lintstagedrc new file mode 100644 index 0000000..08c2cfc --- /dev/null +++ b/.lintstagedrc @@ -0,0 +1,4 @@ +{ + "*.ts?(x)": "eslint --fix", + "*.js?(x)": "eslint --fix" +} diff --git a/.npmrc b/.npmrc deleted file mode 100644 index 7a4ffc4..0000000 --- a/.npmrc +++ /dev/null @@ -1 +0,0 @@ -lockfile=false \ No newline at end of file diff --git a/README.md b/README.md index 3e3447d..9b1ef1c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,5 @@ Packages | Description -------- | ----------- [vite-plugin-cp](packages/vite-plugin-cp) | Copy files after building bundles. [vite-plugin-external](packages/vite-plugin-external) | Provides a way of excluding dependencies from the runtime code and output bundles. -[vite-plugin-include-css](packages/vite-plugin-include-css) | build css into individual js files instead of using css links. [vite-plugin-mock-data](packages/vite-plugin-mock-data) | Provides a simple way to mock data. [vite-plugin-reverse-proxy](packages/vite-plugin-reverse-proxy) | Makes the script to be served with the text/javascript MIME type instead of module MIME type. diff --git a/README_zh_CN.md b/README_zh_CN.md index 9e38894..219df0f 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -8,6 +8,5 @@ -------- | ----------- [vite-plugin-cp](packages/vite-plugin-cp) | 打包之后复制文件到 dist 目录 [vite-plugin-external](packages/vite-plugin-external) | 排出指定模块依赖,支持开发运行时和打包后的bundle文件。 -[vite-plugin-include-css](packages/vite-plugin-include-css) | 将 css 打包到 js 中,使用 link 的方式加载。 [vite-plugin-mock-data](packages/vite-plugin-mock-data) | 本地mock数据。 [vite-plugin-reverse-proxy](packages/vite-plugin-reverse-proxy) | 配合Chrome插件[XSwitch](https://chrome.google.com/webstore/detail/xswitch/idkjhjggpffolpidfkikidcokdkdaogg)将线上资源代理的本地调试。 diff --git a/api.md b/api.md new file mode 100644 index 0000000..2241816 --- /dev/null +++ b/api.md @@ -0,0 +1,8 @@ +> Some custom plugins for vitejs. + +Packages | Description +-------- | ----------- +[vite-plugin-cp](modules/vite_plugin_cp_src.html) | Copy files after building bundles. +[vite-plugin-external](modules/vite_plugin_external_src.html) | Provides a way of excluding dependencies from the runtime code and output bundles. +[vite-plugin-mock-data](modules/vite_plugin_mock-data_src.html) | Provides a simple way to mock data. +[vite-plugin-reverse-proxy](modules/vite_plugin_reverse_proxy_src.html) | Makes the script to be served with the text/javascript MIME type instead of module MIME type. diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000..e2ac661 --- /dev/null +++ b/docs/.nojekyll @@ -0,0 +1 @@ +TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/docs/assets/highlight.css b/docs/assets/highlight.css new file mode 100644 index 0000000..5674cf3 --- /dev/null +++ b/docs/assets/highlight.css @@ -0,0 +1,22 @@ +:root { + --light-code-background: #FFFFFF; + --dark-code-background: #1E1E1E; +} + +@media (prefers-color-scheme: light) { :root { + --code-background: var(--light-code-background); +} } + +@media (prefers-color-scheme: dark) { :root { + --code-background: var(--dark-code-background); +} } + +:root[data-theme='light'] { + --code-background: var(--light-code-background); +} + +:root[data-theme='dark'] { + --code-background: var(--dark-code-background); +} + +pre, code { background: var(--code-background); } diff --git a/docs/assets/main.js b/docs/assets/main.js new file mode 100644 index 0000000..d0aa8d5 --- /dev/null +++ b/docs/assets/main.js @@ -0,0 +1,59 @@ +"use strict"; +"use strict";(()=>{var Pe=Object.create;var ne=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Me=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Fe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oe(e))!Re.call(t,i)&&i!==n&&ne(t,i,{get:()=>e[i],enumerable:!(r=Ie(e,i))||r.enumerable});return t};var De=(t,e,n)=>(n=t!=null?Pe(_e(t)):{},Fe(e||!t||!t.__esModule?ne(n,"default",{value:t,enumerable:!0}):n,t));var ae=Me((se,oe)=>{(function(){var t=function(e){var n=new t.Builder;return n.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),n.searchPipeline.add(t.stemmer),e.call(n,n),n.build()};t.version="2.3.9";t.utils={},t.utils.warn=function(e){return function(n){e.console&&console.warn&&console.warn(n)}}(this),t.utils.asString=function(e){return e==null?"":e.toString()},t.utils.clone=function(e){if(e==null)return e;for(var n=Object.create(null),r=Object.keys(e),i=0;i0){var d=t.utils.clone(n)||{};d.position=[a,u],d.index=s.length,s.push(new t.Token(r.slice(a,o),d))}a=o+1}}return s},t.tokenizer.separator=/[\s\-]+/;t.Pipeline=function(){this._stack=[]},t.Pipeline.registeredFunctions=Object.create(null),t.Pipeline.registerFunction=function(e,n){n in this.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+n),e.label=n,t.Pipeline.registeredFunctions[e.label]=e},t.Pipeline.warnIfFunctionNotRegistered=function(e){var n=e.label&&e.label in this.registeredFunctions;n||t.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. +`,e)},t.Pipeline.load=function(e){var n=new t.Pipeline;return e.forEach(function(r){var i=t.Pipeline.registeredFunctions[r];if(i)n.add(i);else throw new Error("Cannot load unregistered function: "+r)}),n},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(n){t.Pipeline.warnIfFunctionNotRegistered(n),this._stack.push(n)},this)},t.Pipeline.prototype.after=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var r=this._stack.indexOf(e);if(r==-1)throw new Error("Cannot find existingFn");r=r+1,this._stack.splice(r,0,n)},t.Pipeline.prototype.before=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var r=this._stack.indexOf(e);if(r==-1)throw new Error("Cannot find existingFn");this._stack.splice(r,0,n)},t.Pipeline.prototype.remove=function(e){var n=this._stack.indexOf(e);n!=-1&&this._stack.splice(n,1)},t.Pipeline.prototype.run=function(e){for(var n=this._stack.length,r=0;r1&&(oe&&(r=s),o!=e);)i=r-n,s=n+Math.floor(i/2),o=this.elements[s*2];if(o==e||o>e)return s*2;if(ol?d+=2:a==l&&(n+=r[u+1]*i[d+1],u+=2,d+=2);return n},t.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},t.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),n=1,r=0;n0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new t.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var l=s.node.edges["*"];else{var l=new t.TokenSet;s.node.edges["*"]=l}if(s.str.length==0&&(l.final=!0),i.push({node:l,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new t.TokenSet;s.node.edges["*"]=u}s.str.length==1&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var d=s.str.charAt(0),v=s.str.charAt(1),f;v in s.node.edges?f=s.node.edges[v]:(f=new t.TokenSet,s.node.edges[v]=f),s.str.length==1&&(f.final=!0),i.push({node:f,editsRemaining:s.editsRemaining-1,str:d+s.str.slice(2)})}}}return r},t.TokenSet.fromString=function(e){for(var n=new t.TokenSet,r=n,i=0,s=e.length;i=e;n--){var r=this.uncheckedNodes[n],i=r.child.toString();i in this.minimizedNodes?r.parent.edges[r.char]=this.minimizedNodes[i]:(r.child._str=i,this.minimizedNodes[i]=r.child),this.uncheckedNodes.pop()}};t.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},t.Index.prototype.search=function(e){return this.query(function(n){var r=new t.QueryParser(e,n);r.parse()})},t.Index.prototype.query=function(e){for(var n=new t.Query(this.fields),r=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),l=0;l1?this._b=1:this._b=e},t.Builder.prototype.k1=function(e){this._k1=e},t.Builder.prototype.add=function(e,n){var r=e[this._ref],i=Object.keys(this._fields);this._documents[r]=n||{},this.documentCount+=1;for(var s=0;s=this.length)return t.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},t.QueryLexer.prototype.width=function(){return this.pos-this.start},t.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},t.QueryLexer.prototype.backup=function(){this.pos-=1},t.QueryLexer.prototype.acceptDigitRun=function(){var e,n;do e=this.next(),n=e.charCodeAt(0);while(n>47&&n<58);e!=t.QueryLexer.EOS&&this.backup()},t.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(t.QueryLexer.TERM)),e.ignore(),e.more())return t.QueryLexer.lexText},t.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.EDIT_DISTANCE),t.QueryLexer.lexText},t.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.BOOST),t.QueryLexer.lexText},t.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(t.QueryLexer.TERM)},t.QueryLexer.termSeparator=t.tokenizer.separator,t.QueryLexer.lexText=function(e){for(;;){var n=e.next();if(n==t.QueryLexer.EOS)return t.QueryLexer.lexEOS;if(n.charCodeAt(0)==92){e.escapeCharacter();continue}if(n==":")return t.QueryLexer.lexField;if(n=="~")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexEditDistance;if(n=="^")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexBoost;if(n=="+"&&e.width()===1||n=="-"&&e.width()===1)return e.emit(t.QueryLexer.PRESENCE),t.QueryLexer.lexText;if(n.match(t.QueryLexer.termSeparator))return t.QueryLexer.lexTerm}},t.QueryParser=function(e,n){this.lexer=new t.QueryLexer(e),this.query=n,this.currentClause={},this.lexemeIdx=0},t.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=t.QueryParser.parseClause;e;)e=e(this);return this.query},t.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},t.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},t.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},t.QueryParser.parseClause=function(e){var n=e.peekLexeme();if(n!=null)switch(n.type){case t.QueryLexer.PRESENCE:return t.QueryParser.parsePresence;case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var r="expected either a field or a term, found "+n.type;throw n.str.length>=1&&(r+=" with value '"+n.str+"'"),new t.QueryParseError(r,n.start,n.end)}},t.QueryParser.parsePresence=function(e){var n=e.consumeLexeme();if(n!=null){switch(n.str){case"-":e.currentClause.presence=t.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=t.Query.presence.REQUIRED;break;default:var r="unrecognised presence operator'"+n.str+"'";throw new t.QueryParseError(r,n.start,n.end)}var i=e.peekLexeme();if(i==null){var r="expecting term or field, found nothing";throw new t.QueryParseError(r,n.start,n.end)}switch(i.type){case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var r="expecting term or field, found '"+i.type+"'";throw new t.QueryParseError(r,i.start,i.end)}}},t.QueryParser.parseField=function(e){var n=e.consumeLexeme();if(n!=null){if(e.query.allFields.indexOf(n.str)==-1){var r=e.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+n.str+"', possible fields: "+r;throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.fields=[n.str];var s=e.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new t.QueryParseError(i,n.start,n.end)}switch(s.type){case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseTerm=function(e){var n=e.consumeLexeme();if(n!=null){e.currentClause.term=n.str.toLowerCase(),n.str.indexOf("*")!=-1&&(e.currentClause.usePipeline=!1);var r=e.peekLexeme();if(r==null){e.nextClause();return}switch(r.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+r.type+"'";throw new t.QueryParseError(i,r.start,r.end)}}},t.QueryParser.parseEditDistance=function(e){var n=e.consumeLexeme();if(n!=null){var r=parseInt(n.str,10);if(isNaN(r)){var i="edit distance must be numeric";throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.editDistance=r;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseBoost=function(e){var n=e.consumeLexeme();if(n!=null){var r=parseInt(n.str,10);if(isNaN(r)){var i="boost must be numeric";throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.boost=r;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},function(e,n){typeof define=="function"&&define.amd?define(n):typeof se=="object"?oe.exports=n():e.lunr=n()}(this,function(){return t})})()});var re=[];function G(t,e){re.push({selector:e,constructor:t})}var U=class{constructor(){this.alwaysVisibleMember=null;this.createComponents(document.body),this.ensureActivePageVisible(),this.ensureFocusedElementVisible(),this.listenForCodeCopies(),window.addEventListener("hashchange",()=>this.ensureFocusedElementVisible())}createComponents(e){re.forEach(n=>{e.querySelectorAll(n.selector).forEach(r=>{r.dataset.hasInstance||(new n.constructor({el:r,app:this}),r.dataset.hasInstance=String(!0))})})}filterChanged(){this.ensureFocusedElementVisible()}ensureActivePageVisible(){let e=document.querySelector(".tsd-navigation .current"),n=e?.parentElement;for(;n&&!n.classList.contains(".tsd-navigation");)n instanceof HTMLDetailsElement&&(n.open=!0),n=n.parentElement;if(e){let r=e.getBoundingClientRect().top-document.documentElement.clientHeight/4;document.querySelector(".site-menu").scrollTop=r}}ensureFocusedElementVisible(){if(this.alwaysVisibleMember&&(this.alwaysVisibleMember.classList.remove("always-visible"),this.alwaysVisibleMember.firstElementChild.remove(),this.alwaysVisibleMember=null),!location.hash)return;let e=document.getElementById(location.hash.substring(1));if(!e)return;let n=e.parentElement;for(;n&&n.tagName!=="SECTION";)n=n.parentElement;if(n&&n.offsetParent==null){this.alwaysVisibleMember=n,n.classList.add("always-visible");let r=document.createElement("p");r.classList.add("warning"),r.textContent="This member is normally hidden due to your filter settings.",n.prepend(r)}}listenForCodeCopies(){document.querySelectorAll("pre > button").forEach(e=>{let n;e.addEventListener("click",()=>{e.previousElementSibling instanceof HTMLElement&&navigator.clipboard.writeText(e.previousElementSibling.innerText.trim()),e.textContent="Copied!",e.classList.add("visible"),clearTimeout(n),n=setTimeout(()=>{e.classList.remove("visible"),n=setTimeout(()=>{e.textContent="Copy"},100)},1e3)})})}};var ie=(t,e=100)=>{let n;return()=>{clearTimeout(n),n=setTimeout(()=>t(),e)}};var de=De(ae());async function le(t,e){if(!window.searchData)return;let n=await fetch(window.searchData),r=new Blob([await n.arrayBuffer()]).stream().pipeThrough(new DecompressionStream("gzip")),i=await new Response(r).json();t.data=i,t.index=de.Index.load(i.index),e.classList.remove("loading"),e.classList.add("ready")}function he(){let t=document.getElementById("tsd-search");if(!t)return;let e={base:t.dataset.base+"/"},n=document.getElementById("tsd-search-script");t.classList.add("loading"),n&&(n.addEventListener("error",()=>{t.classList.remove("loading"),t.classList.add("failure")}),n.addEventListener("load",()=>{le(e,t)}),le(e,t));let r=document.querySelector("#tsd-search input"),i=document.querySelector("#tsd-search .results");if(!r||!i)throw new Error("The input field or the result list wrapper was not found");let s=!1;i.addEventListener("mousedown",()=>s=!0),i.addEventListener("mouseup",()=>{s=!1,t.classList.remove("has-focus")}),r.addEventListener("focus",()=>t.classList.add("has-focus")),r.addEventListener("blur",()=>{s||(s=!1,t.classList.remove("has-focus"))}),Ae(t,i,r,e)}function Ae(t,e,n,r){n.addEventListener("input",ie(()=>{Ne(t,e,n,r)},200));let i=!1;n.addEventListener("keydown",s=>{i=!0,s.key=="Enter"?Ve(e,n):s.key=="Escape"?n.blur():s.key=="ArrowUp"?ue(e,-1):s.key==="ArrowDown"?ue(e,1):i=!1}),n.addEventListener("keypress",s=>{i&&s.preventDefault()}),document.body.addEventListener("keydown",s=>{s.altKey||s.ctrlKey||s.metaKey||!n.matches(":focus")&&s.key==="/"&&(n.focus(),s.preventDefault())})}function Ne(t,e,n,r){if(!r.index||!r.data)return;e.textContent="";let i=n.value.trim(),s;if(i){let o=i.split(" ").map(a=>a.length?`*${a}*`:"").join(" ");s=r.index.search(o)}else s=[];for(let o=0;oa.score-o.score);for(let o=0,a=Math.min(10,s.length);o`,d=ce(l.name,i);globalThis.DEBUG_SEARCH_WEIGHTS&&(d+=` (score: ${s[o].score.toFixed(2)})`),l.parent&&(d=` + ${ce(l.parent,i)}.${d}`);let v=document.createElement("li");v.classList.value=l.classes??"";let f=document.createElement("a");f.href=r.base+l.url,f.innerHTML=u+d,v.append(f),e.appendChild(v)}}function ue(t,e){let n=t.querySelector(".current");if(!n)n=t.querySelector(e==1?"li:first-child":"li:last-child"),n&&n.classList.add("current");else{let r=n;if(e===1)do r=r.nextElementSibling??void 0;while(r instanceof HTMLElement&&r.offsetParent==null);else do r=r.previousElementSibling??void 0;while(r instanceof HTMLElement&&r.offsetParent==null);r&&(n.classList.remove("current"),r.classList.add("current"))}}function Ve(t,e){let n=t.querySelector(".current");if(n||(n=t.querySelector("li:first-child")),n){let r=n.querySelector("a");r&&(window.location.href=r.href),e.blur()}}function ce(t,e){if(e==="")return t;let n=t.toLocaleLowerCase(),r=e.toLocaleLowerCase(),i=[],s=0,o=n.indexOf(r);for(;o!=-1;)i.push(K(t.substring(s,o)),`${K(t.substring(o,o+r.length))}`),s=o+r.length,o=n.indexOf(r,s);return i.push(K(t.substring(s))),i.join("")}var Be={"&":"&","<":"<",">":">","'":"'",'"':"""};function K(t){return t.replace(/[&<>"'"]/g,e=>Be[e])}var C=class{constructor(e){this.el=e.el,this.app=e.app}};var F="mousedown",pe="mousemove",B="mouseup",J={x:0,y:0},fe=!1,ee=!1,He=!1,D=!1,me=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);document.documentElement.classList.add(me?"is-mobile":"not-mobile");me&&"ontouchstart"in document.documentElement&&(He=!0,F="touchstart",pe="touchmove",B="touchend");document.addEventListener(F,t=>{ee=!0,D=!1;let e=F=="touchstart"?t.targetTouches[0]:t;J.y=e.pageY||0,J.x=e.pageX||0});document.addEventListener(pe,t=>{if(ee&&!D){let e=F=="touchstart"?t.targetTouches[0]:t,n=J.x-(e.pageX||0),r=J.y-(e.pageY||0);D=Math.sqrt(n*n+r*r)>10}});document.addEventListener(B,()=>{ee=!1});document.addEventListener("click",t=>{fe&&(t.preventDefault(),t.stopImmediatePropagation(),fe=!1)});var X=class extends C{constructor(n){super(n);this.className=this.el.dataset.toggle||"",this.el.addEventListener(B,r=>this.onPointerUp(r)),this.el.addEventListener("click",r=>r.preventDefault()),document.addEventListener(F,r=>this.onDocumentPointerDown(r)),document.addEventListener(B,r=>this.onDocumentPointerUp(r))}setActive(n){if(this.active==n)return;this.active=n,document.documentElement.classList.toggle("has-"+this.className,n),this.el.classList.toggle("active",n);let r=(this.active?"to-has-":"from-has-")+this.className;document.documentElement.classList.add(r),setTimeout(()=>document.documentElement.classList.remove(r),500)}onPointerUp(n){D||(this.setActive(!0),n.preventDefault())}onDocumentPointerDown(n){if(this.active){if(n.target.closest(".col-sidebar, .tsd-filter-group"))return;this.setActive(!1)}}onDocumentPointerUp(n){if(!D&&this.active&&n.target.closest(".col-sidebar")){let r=n.target.closest("a");if(r){let i=window.location.href;i.indexOf("#")!=-1&&(i=i.substring(0,i.indexOf("#"))),r.href.substring(0,i.length)==i&&setTimeout(()=>this.setActive(!1),250)}}}};var te;try{te=localStorage}catch{te={getItem(){return null},setItem(){}}}var Q=te;var ve=document.head.appendChild(document.createElement("style"));ve.dataset.for="filters";var Y=class extends C{constructor(n){super(n);this.key=`filter-${this.el.name}`,this.value=this.el.checked,this.el.addEventListener("change",()=>{this.setLocalStorage(this.el.checked)}),this.setLocalStorage(this.fromLocalStorage()),ve.innerHTML+=`html:not(.${this.key}) .tsd-is-${this.el.name} { display: none; } +`}fromLocalStorage(){let n=Q.getItem(this.key);return n?n==="true":this.el.checked}setLocalStorage(n){Q.setItem(this.key,n.toString()),this.value=n,this.handleValueChange()}handleValueChange(){this.el.checked=this.value,document.documentElement.classList.toggle(this.key,this.value),this.app.filterChanged(),document.querySelectorAll(".tsd-index-section").forEach(n=>{n.style.display="block";let r=Array.from(n.querySelectorAll(".tsd-index-link")).every(i=>i.offsetParent==null);n.style.display=r?"none":"block"})}};var Z=class extends C{constructor(n){super(n);this.summary=this.el.querySelector(".tsd-accordion-summary"),this.icon=this.summary.querySelector("svg"),this.key=`tsd-accordion-${this.summary.dataset.key??this.summary.textContent.trim().replace(/\s+/g,"-").toLowerCase()}`;let r=Q.getItem(this.key);this.el.open=r?r==="true":this.el.open,this.el.addEventListener("toggle",()=>this.update());let i=this.summary.querySelector("a");i&&i.addEventListener("click",()=>{location.assign(i.href)}),this.update()}update(){this.icon.style.transform=`rotate(${this.el.open?0:-90}deg)`,Q.setItem(this.key,this.el.open.toString())}};function ge(t){let e=Q.getItem("tsd-theme")||"os";t.value=e,ye(e),t.addEventListener("change",()=>{Q.setItem("tsd-theme",t.value),ye(t.value)})}function ye(t){document.documentElement.dataset.theme=t}var Le;function be(){let t=document.getElementById("tsd-nav-script");t&&(t.addEventListener("load",xe),xe())}async function xe(){let t=document.getElementById("tsd-nav-container");if(!t||!window.navigationData)return;let n=await(await fetch(window.navigationData)).arrayBuffer(),r=new Blob([n]).stream().pipeThrough(new DecompressionStream("gzip")),i=await new Response(r).json();Le=t.dataset.base+"/",t.innerHTML="";for(let s of i)we(s,t,[]);window.app.createComponents(t),window.app.ensureActivePageVisible()}function we(t,e,n){let r=e.appendChild(document.createElement("li"));if(t.children){let i=[...n,t.text],s=r.appendChild(document.createElement("details"));s.className=t.class?`${t.class} tsd-index-accordion`:"tsd-index-accordion",s.dataset.key=i.join("$");let o=s.appendChild(document.createElement("summary"));o.className="tsd-accordion-summary",o.innerHTML='',Ee(t,o);let a=s.appendChild(document.createElement("div"));a.className="tsd-accordion-details";let l=a.appendChild(document.createElement("ul"));l.className="tsd-nested-navigation";for(let u of t.children)we(u,l,i)}else Ee(t,r,t.class)}function Ee(t,e,n){if(t.path){let r=e.appendChild(document.createElement("a"));r.href=Le+t.path,n&&(r.className=n),location.href===r.href&&r.classList.add("current"),t.kind&&(r.innerHTML=``),r.appendChild(document.createElement("span")).textContent=t.text}else e.appendChild(document.createElement("span")).textContent=t.text}G(X,"a[data-toggle]");G(Z,".tsd-index-accordion");G(Y,".tsd-filter-item input[type=checkbox]");var Se=document.getElementById("tsd-theme");Se&&ge(Se);var je=new U;Object.defineProperty(window,"app",{value:je});he();be();})(); +/*! Bundled license information: + +lunr/lunr.js: + (** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9 + * Copyright (C) 2020 Oliver Nightingale + * @license MIT + *) + (*! + * lunr.utils + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.Set + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.tokenizer + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.Pipeline + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.Vector + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.stemmer + * Copyright (C) 2020 Oliver Nightingale + * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt + *) + (*! + * lunr.stopWordFilter + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.trimmer + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.TokenSet + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.Index + * Copyright (C) 2020 Oliver Nightingale + *) + (*! + * lunr.Builder + * Copyright (C) 2020 Oliver Nightingale + *) +*/ diff --git a/docs/assets/navigation.js b/docs/assets/navigation.js new file mode 100644 index 0000000..5f37c19 --- /dev/null +++ b/docs/assets/navigation.js @@ -0,0 +1 @@ +window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAE62VvW6DMBRG38UzNFLVZmBsl26VqmxRZFn2BSyMjfwTpary7jWEpnaSBlMxYs493PsZw/YLWThYVKA9t5B3wlVc5rRbGU1Rhjpia3+vVcwJMKuewScG0w575qG2rfBgwyVDxWOGaM0F0yBRsT2r3zvLlTS/Pi4t6JLQ28oRv1A/r4/Z2bghugKbKjzR93wMSuJEICydpEMXt3wjHQvXT8ddYAzj9CugJRHTof6QydG+EMNpar6RPay8F82/5AnexMgj7dzga6Wa3BmYDr4nsSeTg09sP/LObZ9LKhyDnBozPcEIYw8vPcSleu4craJNzogl01P0KO7R5BneiGQCPpSzMPmOxvagcokDEMsTTsDw5FclS17NlAeVCxyx2D13czXsQRt/qdXhc3qDRxwP+OJ/kGv7cl+ia/ffUe2+AYA632ZYBwAA" \ No newline at end of file diff --git a/docs/assets/search.js b/docs/assets/search.js new file mode 100644 index 0000000..fd1c264 --- /dev/null +++ b/docs/assets/search.js @@ -0,0 +1 @@ +window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAE71bS3OjRhD+L+iKtZqXhHzbJIfkkEpVKpWLy6XCErKpRUIF2LtbLv/3zMAA3fK0eAjlsjKrfnzdX09PM6B3L0u/5979w7v3LT7uvHvue8fwEHn33ltcRHen5PU5Pt5tT1/ybOv53muW6K8O6e41ifIvRmRTiWy2p40Wmb8Uh0TLbZMwzyNt2PM+/Ma2WjbW/wmz56hoLMbHIsr24dZttBJ22Pa9U5hFx8INt/XMFlw2rmEkvf3OKq2+vq0qBWEX5SNin1m1iUBoPfPHcBiN4kRA9klYFNFxBJJWcyIoz0n69PTzr1MRp8d8BKBz/YlgFVl4zPdpdhgBCeqOh7NUSrSrd7Mpfp7GlE4DZt6YGIhp3sbj7izDyLPSU/WWlzT9NsLzzOr1zkUdJAEjOuoEbfsShJC0qlOBGbOmEKTRi6oD2Pb7bgycSm0qEEVZ1aPy0qpeAWYJd6V9+Jq0G9P+9bgtxV1IrPAVC8c9akQ/dPzHMOkcOGrBQWPHL2Eeb3uWInIAFfvHjIIZX4WXkfQuSIgGmSGhhduX6Lc4uxZfa+YGIGuFK/mcQTvTwByxKyGMNym3XfQWJenpYLTHgplhIwOz1cHnKdOLvew74/EhG9PC06H/me46t9aLubMGpgXWc8+ngQ3Z+YcAG9rgLva2It/dxfldfHyJMm1gNwnAMW2uu8PdAuq4Ztejz00EdvA0gXAOnimIhueeLMyMffeaR52ThRHcaMHOyWJwtMjy4GhRAF3Rxsdt8rqL7rZ53hmwld1o2eljPjc+OOzzSLoiP6Tbb3e7sAg74zaSGyM5aIb8PTzukujv9LXobLbYAVDsHz2OhjpBiZMrscysiYGAoB3ynrgU6eyuHfhaKzeAmPabzjogpgPuUAdDzIs0u5bj2sY08OCaKL/7NT3u4+dhGIHi9WtixMCN0QyeuHutzh4DEA2j990dpqxjjojzr/ti6JpEsFoLE0Mzwl+1wSLvMZJdAHhu5wYwy+LNrq60mcvWreBOgvOmAK+nHdq5HubgiQejGzzvkN3NOe1k+lY8y/Vllv742TnxWOlNKT1o6ulZ5Z8dDO6pnyO67uj0MqRBp6ifoHUfZkTh4SnRO1z3kUEHzjNT04AdXNufQQ6u70v8XnzMNAbRrL4Y8Lzpc+JqI3WOCLbR89QJ0M57P2fthFzHDxb3QgbtiIJHtymwNyb/L/R/R3mavEW7G0QBTN8+miQNp43BGpwS+aOvu9gu+uHdv3tGx5y03nt8LuZrbXwfR8nOvFVSr4hteijPih/td/9GW30rYiQqkS8Lz39Y+EzOeeAz+8l9LuarBX989B9qC6Vg+R+lGtNXwpeLuWRLJMaQGNdX0iXGkZjQV8olJpCY1FdLl5hEYkpfrVxiCokt9VXgCzkP2BqJLZHYSl+tXdZWSCzQV2zhMhcgubWRYz5fzlnAkNwaJ9jkm3GXQXZGhUk5E05JzAbjVMgM88FM3pn0eTAXqzNJTAkzqWfKaROzwkz22dLnci4UjpxhYtjSUZNs5SpKhrlihhMWOOsS08UCOkJMGCsZWzsjxJRxwwt31gDHlHFGVgE/W0CGGM6cSwhzxg0xnDslMWfcEMOdq5djzrgiS4tjzviSzCfHHPEVmU+OOeIBnU/MEV+TtcUxR8L2OzYPhDDFZf/gPlvO1zrReqhg6/lSYisC8ycY6U9g/gR3+uPKetEl4PR31h8F7Q9zK6Tb36rxFzj9Yd6FIZc7u57AvAtDrlg4JTHvwpArnJUsMO8iIFeHwLwLQ65w1rzAvEtDoHDWvMTcSnptSsyt5GTNS8yfNCQJ50Yoz7Y4Q4Rw7oUScyQNEcK9HWKOZMmRc0eUmCNZcuTsnxJzJAOyIiXmSK6dFSnWdUXKhasiJeZPLUhWFOZPMXJHUpg/VU4nzopUmD9Frz+F+VOSnAPU2ZRiSJLO2lWYP2VIks7aVZg/ZUiSzjpTmD9lSJLOOlMVf+WgqSfMItr9UQ2cemSs7+XevY2dQnWsdnx+9wL9z4fv6UD150c7fJor4+HJvK3RnNUDG0FrQ+/TbuXySe/OnCwBxTVQXFfeOWnA3ha16jqnjbrO5CW1rLkPAeoSqJNe7QvcrRpvtRaUUv3oEGgtWzW9OxB63xFABgDqua1MD7Mk8WX1KSlb7XM8AAIQJSiWm+MMAASA18NeBcDypTfM6tMClHUVCdJ+jowrgIlUAW/NgHBYq8rJPERvh/LgB+iBuuFUGpqXOkAagB6zYXNF6aPX8YCRFTBCFS141QDABkuVL6z7gLBQPZVslQVQFpTb5q3wVg+gpSKt3jJ19AVQbbZaGcVS85ASIAbsCmp5Wr3qkTJIFWgsgsJdvToMmAErm9n8CmqJ22fryKnqscTjPKye/oBAwTKX1BKojiJA8wLOFFUE5kAcIVz1WP9GKSwf/5x1awFcykvaJR2ZoyAE6COSoqWxgFUBdEnVb6t6Dh2UoqRqqTpyASkG9aAotK7tEBRuvanVTdI2R2mvFVVe1bkSsnq27fi2e9Q16tua8y2z2smaMm4PxLdnfVECH4oqYPiGIKgskCtO1TB40gKcgsZEIq5/ONOqwUoilcpDOVQH6z7OTAV9njYE6P6S4u08OJAVSqN6tQD4AakUFMbC/goMqIHmdVEJ1ypY08zWjSL12x/EtBZARqmF1bw6BuoFZIbsseaEFSotJloCejQ+xacoiY/a1sPjx8d/5dg9gc03AAA="; \ No newline at end of file diff --git a/docs/assets/style.css b/docs/assets/style.css new file mode 100644 index 0000000..07a385b --- /dev/null +++ b/docs/assets/style.css @@ -0,0 +1,1394 @@ +:root { + /* Light */ + --light-color-background: #f2f4f8; + --light-color-background-secondary: #eff0f1; + --light-color-warning-text: #222; + --light-color-background-warning: #e6e600; + --light-color-icon-background: var(--light-color-background); + --light-color-accent: #c5c7c9; + --light-color-active-menu-item: var(--light-color-accent); + --light-color-text: #222; + --light-color-text-aside: #6e6e6e; + --light-color-link: #1f70c2; + + --light-color-ts-keyword: #056bd6; + --light-color-ts-project: #b111c9; + --light-color-ts-module: var(--light-color-ts-project); + --light-color-ts-namespace: var(--light-color-ts-project); + --light-color-ts-enum: #7e6f15; + --light-color-ts-enum-member: var(--light-color-ts-enum); + --light-color-ts-variable: #4760ec; + --light-color-ts-function: #572be7; + --light-color-ts-class: #1f70c2; + --light-color-ts-interface: #108024; + --light-color-ts-constructor: var(--light-color-ts-class); + --light-color-ts-property: var(--light-color-ts-variable); + --light-color-ts-method: var(--light-color-ts-function); + --light-color-ts-call-signature: var(--light-color-ts-method); + --light-color-ts-index-signature: var(--light-color-ts-property); + --light-color-ts-constructor-signature: var(--light-color-ts-constructor); + --light-color-ts-parameter: var(--light-color-ts-variable); + /* type literal not included as links will never be generated to it */ + --light-color-ts-type-parameter: var(--light-color-ts-type-alias); + --light-color-ts-accessor: var(--light-color-ts-property); + --light-color-ts-get-signature: var(--light-color-ts-accessor); + --light-color-ts-set-signature: var(--light-color-ts-accessor); + --light-color-ts-type-alias: #d51270; + /* reference not included as links will be colored with the kind that it points to */ + + --light-external-icon: url("data:image/svg+xml;utf8,"); + --light-color-scheme: light; + + /* Dark */ + --dark-color-background: #2b2e33; + --dark-color-background-secondary: #1e2024; + --dark-color-background-warning: #bebe00; + --dark-color-warning-text: #222; + --dark-color-icon-background: var(--dark-color-background-secondary); + --dark-color-accent: #9096a2; + --dark-color-active-menu-item: #5d5d6a; + --dark-color-text: #f5f5f5; + --dark-color-text-aside: #dddddd; + --dark-color-link: #00aff4; + + --dark-color-ts-keyword: #3399ff; + --dark-color-ts-project: #e358ff; + --dark-color-ts-module: var(--dark-color-ts-project); + --dark-color-ts-namespace: var(--dark-color-ts-project); + --dark-color-ts-enum: #f4d93e; + --dark-color-ts-enum-member: var(--dark-color-ts-enum); + --dark-color-ts-variable: #798dff; + --dark-color-ts-function: #a280ff; + --dark-color-ts-class: #8ac4ff; + --dark-color-ts-interface: #6cff87; + --dark-color-ts-constructor: var(--dark-color-ts-class); + --dark-color-ts-property: var(--dark-color-ts-variable); + --dark-color-ts-method: var(--dark-color-ts-function); + --dark-color-ts-call-signature: var(--dark-color-ts-method); + --dark-color-ts-index-signature: var(--dark-color-ts-property); + --dark-color-ts-constructor-signature: var(--dark-color-ts-constructor); + --dark-color-ts-parameter: var(--dark-color-ts-variable); + /* type literal not included as links will never be generated to it */ + --dark-color-ts-type-parameter: var(--dark-color-ts-type-alias); + --dark-color-ts-accessor: var(--dark-color-ts-property); + --dark-color-ts-get-signature: var(--dark-color-ts-accessor); + --dark-color-ts-set-signature: var(--dark-color-ts-accessor); + --dark-color-ts-type-alias: #ff6492; + /* reference not included as links will be colored with the kind that it points to */ + + --dark-external-icon: url("data:image/svg+xml;utf8,"); + --dark-color-scheme: dark; +} + +@media (prefers-color-scheme: light) { + :root { + --color-background: var(--light-color-background); + --color-background-secondary: var(--light-color-background-secondary); + --color-background-warning: var(--light-color-background-warning); + --color-warning-text: var(--light-color-warning-text); + --color-icon-background: var(--light-color-icon-background); + --color-accent: var(--light-color-accent); + --color-active-menu-item: var(--light-color-active-menu-item); + --color-text: var(--light-color-text); + --color-text-aside: var(--light-color-text-aside); + --color-link: var(--light-color-link); + + --color-ts-keyword: var(--light-color-ts-keyword); + --color-ts-module: var(--light-color-ts-module); + --color-ts-namespace: var(--light-color-ts-namespace); + --color-ts-enum: var(--light-color-ts-enum); + --color-ts-enum-member: var(--light-color-ts-enum-member); + --color-ts-variable: var(--light-color-ts-variable); + --color-ts-function: var(--light-color-ts-function); + --color-ts-class: var(--light-color-ts-class); + --color-ts-interface: var(--light-color-ts-interface); + --color-ts-constructor: var(--light-color-ts-constructor); + --color-ts-property: var(--light-color-ts-property); + --color-ts-method: var(--light-color-ts-method); + --color-ts-call-signature: var(--light-color-ts-call-signature); + --color-ts-index-signature: var(--light-color-ts-index-signature); + --color-ts-constructor-signature: var( + --light-color-ts-constructor-signature + ); + --color-ts-parameter: var(--light-color-ts-parameter); + --color-ts-type-parameter: var(--light-color-ts-type-parameter); + --color-ts-accessor: var(--light-color-ts-accessor); + --color-ts-get-signature: var(--light-color-ts-get-signature); + --color-ts-set-signature: var(--light-color-ts-set-signature); + --color-ts-type-alias: var(--light-color-ts-type-alias); + + --external-icon: var(--light-external-icon); + --color-scheme: var(--light-color-scheme); + } +} + +@media (prefers-color-scheme: dark) { + :root { + --color-background: var(--dark-color-background); + --color-background-secondary: var(--dark-color-background-secondary); + --color-background-warning: var(--dark-color-background-warning); + --color-warning-text: var(--dark-color-warning-text); + --color-icon-background: var(--dark-color-icon-background); + --color-accent: var(--dark-color-accent); + --color-active-menu-item: var(--dark-color-active-menu-item); + --color-text: var(--dark-color-text); + --color-text-aside: var(--dark-color-text-aside); + --color-link: var(--dark-color-link); + + --color-ts-keyword: var(--dark-color-ts-keyword); + --color-ts-module: var(--dark-color-ts-module); + --color-ts-namespace: var(--dark-color-ts-namespace); + --color-ts-enum: var(--dark-color-ts-enum); + --color-ts-enum-member: var(--dark-color-ts-enum-member); + --color-ts-variable: var(--dark-color-ts-variable); + --color-ts-function: var(--dark-color-ts-function); + --color-ts-class: var(--dark-color-ts-class); + --color-ts-interface: var(--dark-color-ts-interface); + --color-ts-constructor: var(--dark-color-ts-constructor); + --color-ts-property: var(--dark-color-ts-property); + --color-ts-method: var(--dark-color-ts-method); + --color-ts-call-signature: var(--dark-color-ts-call-signature); + --color-ts-index-signature: var(--dark-color-ts-index-signature); + --color-ts-constructor-signature: var( + --dark-color-ts-constructor-signature + ); + --color-ts-parameter: var(--dark-color-ts-parameter); + --color-ts-type-parameter: var(--dark-color-ts-type-parameter); + --color-ts-accessor: var(--dark-color-ts-accessor); + --color-ts-get-signature: var(--dark-color-ts-get-signature); + --color-ts-set-signature: var(--dark-color-ts-set-signature); + --color-ts-type-alias: var(--dark-color-ts-type-alias); + + --external-icon: var(--dark-external-icon); + --color-scheme: var(--dark-color-scheme); + } +} + +html { + color-scheme: var(--color-scheme); +} + +body { + margin: 0; +} + +:root[data-theme="light"] { + --color-background: var(--light-color-background); + --color-background-secondary: var(--light-color-background-secondary); + --color-background-warning: var(--light-color-background-warning); + --color-warning-text: var(--light-color-warning-text); + --color-icon-background: var(--light-color-icon-background); + --color-accent: var(--light-color-accent); + --color-active-menu-item: var(--light-color-active-menu-item); + --color-text: var(--light-color-text); + --color-text-aside: var(--light-color-text-aside); + --color-link: var(--light-color-link); + + --color-ts-keyword: var(--light-color-ts-keyword); + --color-ts-module: var(--light-color-ts-module); + --color-ts-namespace: var(--light-color-ts-namespace); + --color-ts-enum: var(--light-color-ts-enum); + --color-ts-enum-member: var(--light-color-ts-enum-member); + --color-ts-variable: var(--light-color-ts-variable); + --color-ts-function: var(--light-color-ts-function); + --color-ts-class: var(--light-color-ts-class); + --color-ts-interface: var(--light-color-ts-interface); + --color-ts-constructor: var(--light-color-ts-constructor); + --color-ts-property: var(--light-color-ts-property); + --color-ts-method: var(--light-color-ts-method); + --color-ts-call-signature: var(--light-color-ts-call-signature); + --color-ts-index-signature: var(--light-color-ts-index-signature); + --color-ts-constructor-signature: var( + --light-color-ts-constructor-signature + ); + --color-ts-parameter: var(--light-color-ts-parameter); + --color-ts-type-parameter: var(--light-color-ts-type-parameter); + --color-ts-accessor: var(--light-color-ts-accessor); + --color-ts-get-signature: var(--light-color-ts-get-signature); + --color-ts-set-signature: var(--light-color-ts-set-signature); + --color-ts-type-alias: var(--light-color-ts-type-alias); + + --external-icon: var(--light-external-icon); + --color-scheme: var(--light-color-scheme); +} + +:root[data-theme="dark"] { + --color-background: var(--dark-color-background); + --color-background-secondary: var(--dark-color-background-secondary); + --color-background-warning: var(--dark-color-background-warning); + --color-warning-text: var(--dark-color-warning-text); + --color-icon-background: var(--dark-color-icon-background); + --color-accent: var(--dark-color-accent); + --color-active-menu-item: var(--dark-color-active-menu-item); + --color-text: var(--dark-color-text); + --color-text-aside: var(--dark-color-text-aside); + --color-link: var(--dark-color-link); + + --color-ts-keyword: var(--dark-color-ts-keyword); + --color-ts-module: var(--dark-color-ts-module); + --color-ts-namespace: var(--dark-color-ts-namespace); + --color-ts-enum: var(--dark-color-ts-enum); + --color-ts-enum-member: var(--dark-color-ts-enum-member); + --color-ts-variable: var(--dark-color-ts-variable); + --color-ts-function: var(--dark-color-ts-function); + --color-ts-class: var(--dark-color-ts-class); + --color-ts-interface: var(--dark-color-ts-interface); + --color-ts-constructor: var(--dark-color-ts-constructor); + --color-ts-property: var(--dark-color-ts-property); + --color-ts-method: var(--dark-color-ts-method); + --color-ts-call-signature: var(--dark-color-ts-call-signature); + --color-ts-index-signature: var(--dark-color-ts-index-signature); + --color-ts-constructor-signature: var( + --dark-color-ts-constructor-signature + ); + --color-ts-parameter: var(--dark-color-ts-parameter); + --color-ts-type-parameter: var(--dark-color-ts-type-parameter); + --color-ts-accessor: var(--dark-color-ts-accessor); + --color-ts-get-signature: var(--dark-color-ts-get-signature); + --color-ts-set-signature: var(--dark-color-ts-set-signature); + --color-ts-type-alias: var(--dark-color-ts-type-alias); + + --external-icon: var(--dark-external-icon); + --color-scheme: var(--dark-color-scheme); +} + +.always-visible, +.always-visible .tsd-signatures { + display: inherit !important; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + line-height: 1.2; +} + +h1 > a, +h2 > a, +h3 > a, +h4 > a, +h5 > a, +h6 > a { + text-decoration: none; + color: var(--color-text); +} + +h1 { + font-size: 1.875rem; + margin: 0.67rem 0; +} + +h2 { + font-size: 1.5rem; + margin: 0.83rem 0; +} + +h3 { + font-size: 1.25rem; + margin: 1rem 0; +} + +h4 { + font-size: 1.05rem; + margin: 1.33rem 0; +} + +h5 { + font-size: 1rem; + margin: 1.5rem 0; +} + +h6 { + font-size: 0.875rem; + margin: 2.33rem 0; +} + +.uppercase { + text-transform: uppercase; +} + +dl, +menu, +ol, +ul { + margin: 1em 0; +} + +dd { + margin: 0 0 0 40px; +} + +.container { + max-width: 1700px; + padding: 0 2rem; +} + +/* Footer */ +.tsd-generator { + border-top: 1px solid var(--color-accent); + padding-top: 1rem; + padding-bottom: 1rem; + max-height: 3.5rem; +} + +.tsd-generator > p { + margin-top: 0; + margin-bottom: 0; + padding: 0 1rem; +} + +.container-main { + margin: 0 auto; + /* toolbar, footer, margin */ + min-height: calc(100vh - 41px - 56px - 4rem); +} + +@keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +@keyframes fade-out { + from { + opacity: 1; + visibility: visible; + } + to { + opacity: 0; + } +} +@keyframes fade-in-delayed { + 0% { + opacity: 0; + } + 33% { + opacity: 0; + } + 100% { + opacity: 1; + } +} +@keyframes fade-out-delayed { + 0% { + opacity: 1; + visibility: visible; + } + 66% { + opacity: 0; + } + 100% { + opacity: 0; + } +} +@keyframes pop-in-from-right { + from { + transform: translate(100%, 0); + } + to { + transform: translate(0, 0); + } +} +@keyframes pop-out-to-right { + from { + transform: translate(0, 0); + visibility: visible; + } + to { + transform: translate(100%, 0); + } +} +body { + background: var(--color-background); + font-family: "Segoe UI", sans-serif; + font-size: 16px; + color: var(--color-text); +} + +a { + color: var(--color-link); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} +a.external[target="_blank"] { + background-image: var(--external-icon); + background-position: top 3px right; + background-repeat: no-repeat; + padding-right: 13px; +} + +code, +pre { + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; + padding: 0.2em; + margin: 0; + font-size: 0.875rem; + border-radius: 0.8em; +} + +pre { + position: relative; + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; + padding: 10px; + border: 1px solid var(--color-accent); +} +pre code { + padding: 0; + font-size: 100%; +} +pre > button { + position: absolute; + top: 10px; + right: 10px; + opacity: 0; + transition: opacity 0.1s; + box-sizing: border-box; +} +pre:hover > button, +pre > button.visible { + opacity: 1; +} + +blockquote { + margin: 1em 0; + padding-left: 1em; + border-left: 4px solid gray; +} + +.tsd-typography { + line-height: 1.333em; +} +.tsd-typography ul { + list-style: square; + padding: 0 0 0 20px; + margin: 0; +} +.tsd-typography .tsd-index-panel h3, +.tsd-index-panel .tsd-typography h3, +.tsd-typography h4, +.tsd-typography h5, +.tsd-typography h6 { + font-size: 1em; +} +.tsd-typography h5, +.tsd-typography h6 { + font-weight: normal; +} +.tsd-typography p, +.tsd-typography ul, +.tsd-typography ol { + margin: 1em 0; +} +.tsd-typography table { + border-collapse: collapse; + border: none; +} +.tsd-typography td, +.tsd-typography th { + padding: 6px 13px; + border: 1px solid var(--color-accent); +} +.tsd-typography thead, +.tsd-typography tr:nth-child(even) { + background-color: var(--color-background-secondary); +} + +.tsd-breadcrumb { + margin: 0; + padding: 0; + color: var(--color-text-aside); +} +.tsd-breadcrumb a { + color: var(--color-text-aside); + text-decoration: none; +} +.tsd-breadcrumb a:hover { + text-decoration: underline; +} +.tsd-breadcrumb li { + display: inline; +} +.tsd-breadcrumb li:after { + content: " / "; +} + +.tsd-comment-tags { + display: flex; + flex-direction: column; +} +dl.tsd-comment-tag-group { + display: flex; + align-items: center; + overflow: hidden; + margin: 0.5em 0; +} +dl.tsd-comment-tag-group dt { + display: flex; + margin-right: 0.5em; + font-size: 0.875em; + font-weight: normal; +} +dl.tsd-comment-tag-group dd { + margin: 0; +} +code.tsd-tag { + padding: 0.25em 0.4em; + border: 0.1em solid var(--color-accent); + margin-right: 0.25em; + font-size: 70%; +} +h1 code.tsd-tag:first-of-type { + margin-left: 0.25em; +} + +dl.tsd-comment-tag-group dd:before, +dl.tsd-comment-tag-group dd:after { + content: " "; +} +dl.tsd-comment-tag-group dd pre, +dl.tsd-comment-tag-group dd:after { + clear: both; +} +dl.tsd-comment-tag-group p { + margin: 0; +} + +.tsd-panel.tsd-comment .lead { + font-size: 1.1em; + line-height: 1.333em; + margin-bottom: 2em; +} +.tsd-panel.tsd-comment .lead:last-child { + margin-bottom: 0; +} + +.tsd-filter-visibility h4 { + font-size: 1rem; + padding-top: 0.75rem; + padding-bottom: 0.5rem; + margin: 0; +} +.tsd-filter-item:not(:last-child) { + margin-bottom: 0.5rem; +} +.tsd-filter-input { + display: flex; + width: fit-content; + width: -moz-fit-content; + align-items: center; + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + cursor: pointer; +} +.tsd-filter-input input[type="checkbox"] { + cursor: pointer; + position: absolute; + width: 1.5em; + height: 1.5em; + opacity: 0; +} +.tsd-filter-input input[type="checkbox"]:disabled { + pointer-events: none; +} +.tsd-filter-input svg { + cursor: pointer; + width: 1.5em; + height: 1.5em; + margin-right: 0.5em; + border-radius: 0.33em; + /* Leaving this at full opacity breaks event listeners on Firefox. + Don't remove unless you know what you're doing. */ + opacity: 0.99; +} +.tsd-filter-input input[type="checkbox"]:focus + svg { + transform: scale(0.95); +} +.tsd-filter-input input[type="checkbox"]:focus:not(:focus-visible) + svg { + transform: scale(1); +} +.tsd-checkbox-background { + fill: var(--color-accent); +} +input[type="checkbox"]:checked ~ svg .tsd-checkbox-checkmark { + stroke: var(--color-text); +} +.tsd-filter-input input:disabled ~ svg > .tsd-checkbox-background { + fill: var(--color-background); + stroke: var(--color-accent); + stroke-width: 0.25rem; +} +.tsd-filter-input input:disabled ~ svg > .tsd-checkbox-checkmark { + stroke: var(--color-accent); +} + +.tsd-theme-toggle { + padding-top: 0.75rem; +} +.tsd-theme-toggle > h4 { + display: inline; + vertical-align: middle; + margin-right: 0.75rem; +} + +.tsd-hierarchy { + list-style: square; + margin: 0; +} +.tsd-hierarchy .target { + font-weight: bold; +} + +.tsd-panel-group.tsd-index-group { + margin-bottom: 0; +} +.tsd-index-panel .tsd-index-list { + list-style: none; + line-height: 1.333em; + margin: 0; + padding: 0.25rem 0 0 0; + overflow: hidden; + display: grid; + grid-template-columns: repeat(3, 1fr); + column-gap: 1rem; + grid-template-rows: auto; +} +@media (max-width: 1024px) { + .tsd-index-panel .tsd-index-list { + grid-template-columns: repeat(2, 1fr); + } +} +@media (max-width: 768px) { + .tsd-index-panel .tsd-index-list { + grid-template-columns: repeat(1, 1fr); + } +} +.tsd-index-panel .tsd-index-list li { + -webkit-page-break-inside: avoid; + -moz-page-break-inside: avoid; + -ms-page-break-inside: avoid; + -o-page-break-inside: avoid; + page-break-inside: avoid; +} + +.tsd-flag { + display: inline-block; + padding: 0.25em 0.4em; + border-radius: 4px; + color: var(--color-comment-tag-text); + background-color: var(--color-comment-tag); + text-indent: 0; + font-size: 75%; + line-height: 1; + font-weight: normal; +} + +.tsd-anchor { + position: relative; + top: -100px; +} + +.tsd-member { + position: relative; +} +.tsd-member .tsd-anchor + h3 { + display: flex; + align-items: center; + margin-top: 0; + margin-bottom: 0; + border-bottom: none; +} + +.tsd-navigation.settings { + margin: 1rem 0; +} +.tsd-navigation > a, +.tsd-navigation .tsd-accordion-summary { + width: calc(100% - 0.5rem); +} +.tsd-navigation a, +.tsd-navigation summary > span, +.tsd-page-navigation a { + display: inline-flex; + align-items: center; + padding: 0.25rem; + color: var(--color-text); + text-decoration: none; + box-sizing: border-box; +} +.tsd-navigation a.current, +.tsd-page-navigation a.current { + background: var(--color-active-menu-item); +} +.tsd-navigation a:hover, +.tsd-page-navigation a:hover { + text-decoration: underline; +} +.tsd-navigation ul, +.tsd-page-navigation ul { + margin-top: 0; + margin-bottom: 0; + padding: 0; + list-style: none; +} +.tsd-navigation li, +.tsd-page-navigation li { + padding: 0; + max-width: 100%; +} +.tsd-nested-navigation { + margin-left: 3rem; +} +.tsd-nested-navigation > li > details { + margin-left: -1.5rem; +} +.tsd-small-nested-navigation { + margin-left: 1.5rem; +} +.tsd-small-nested-navigation > li > details { + margin-left: -1.5rem; +} + +.tsd-nested-navigation > li > a, +.tsd-nested-navigation > li > span { + width: calc(100% - 1.75rem - 0.5rem); +} + +.tsd-page-navigation ul { + padding-left: 1.75rem; +} + +#tsd-sidebar-links a { + margin-top: 0; + margin-bottom: 0.5rem; + line-height: 1.25rem; +} +#tsd-sidebar-links a:last-of-type { + margin-bottom: 0; +} + +a.tsd-index-link { + padding: 0.25rem 0 !important; + font-size: 1rem; + line-height: 1.25rem; + display: inline-flex; + align-items: center; + color: var(--color-text); +} +.tsd-accordion-summary { + list-style-type: none; /* hide marker on non-safari */ + outline: none; /* broken on safari, so just hide it */ +} +.tsd-accordion-summary::-webkit-details-marker { + display: none; /* hide marker on safari */ +} +.tsd-accordion-summary, +.tsd-accordion-summary a { + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + + cursor: pointer; +} +.tsd-accordion-summary a { + width: calc(100% - 1.5rem); +} +.tsd-accordion-summary > * { + margin-top: 0; + margin-bottom: 0; + padding-top: 0; + padding-bottom: 0; +} +.tsd-index-accordion .tsd-accordion-summary > svg { + margin-left: 0.25rem; +} +.tsd-index-content > :not(:first-child) { + margin-top: 0.75rem; +} +.tsd-index-heading { + margin-top: 1.5rem; + margin-bottom: 0.75rem; +} + +.tsd-kind-icon { + margin-right: 0.5rem; + width: 1.25rem; + height: 1.25rem; + min-width: 1.25rem; + min-height: 1.25rem; +} +.tsd-kind-icon path { + transform-origin: center; + transform: scale(1.1); +} +.tsd-signature > .tsd-kind-icon { + margin-right: 0.8rem; +} + +.tsd-panel { + margin-bottom: 2.5rem; +} +.tsd-panel.tsd-member { + margin-bottom: 4rem; +} +.tsd-panel:empty { + display: none; +} +.tsd-panel > h1, +.tsd-panel > h2, +.tsd-panel > h3 { + margin: 1.5rem -1.5rem 0.75rem -1.5rem; + padding: 0 1.5rem 0.75rem 1.5rem; +} +.tsd-panel > h1.tsd-before-signature, +.tsd-panel > h2.tsd-before-signature, +.tsd-panel > h3.tsd-before-signature { + margin-bottom: 0; + border-bottom: none; +} + +.tsd-panel-group { + margin: 4rem 0; +} +.tsd-panel-group.tsd-index-group { + margin: 2rem 0; +} +.tsd-panel-group.tsd-index-group details { + margin: 2rem 0; +} + +#tsd-search { + transition: background-color 0.2s; +} +#tsd-search .title { + position: relative; + z-index: 2; +} +#tsd-search .field { + position: absolute; + left: 0; + top: 0; + right: 2.5rem; + height: 100%; +} +#tsd-search .field input { + box-sizing: border-box; + position: relative; + top: -50px; + z-index: 1; + width: 100%; + padding: 0 10px; + opacity: 0; + outline: 0; + border: 0; + background: transparent; + color: var(--color-text); +} +#tsd-search .field label { + position: absolute; + overflow: hidden; + right: -40px; +} +#tsd-search .field input, +#tsd-search .title, +#tsd-toolbar-links a { + transition: opacity 0.2s; +} +#tsd-search .results { + position: absolute; + visibility: hidden; + top: 40px; + width: 100%; + margin: 0; + padding: 0; + list-style: none; + box-shadow: 0 0 4px rgba(0, 0, 0, 0.25); +} +#tsd-search .results li { + background-color: var(--color-background); + line-height: initial; + padding: 4px; +} +#tsd-search .results li:nth-child(even) { + background-color: var(--color-background-secondary); +} +#tsd-search .results li.state { + display: none; +} +#tsd-search .results li.current:not(.no-results), +#tsd-search .results li:hover:not(.no-results) { + background-color: var(--color-accent); +} +#tsd-search .results a { + display: flex; + align-items: center; + padding: 0.25rem; + box-sizing: border-box; +} +#tsd-search .results a:before { + top: 10px; +} +#tsd-search .results span.parent { + color: var(--color-text-aside); + font-weight: normal; +} +#tsd-search.has-focus { + background-color: var(--color-accent); +} +#tsd-search.has-focus .field input { + top: 0; + opacity: 1; +} +#tsd-search.has-focus .title, +#tsd-search.has-focus #tsd-toolbar-links a { + z-index: 0; + opacity: 0; +} +#tsd-search.has-focus .results { + visibility: visible; +} +#tsd-search.loading .results li.state.loading { + display: block; +} +#tsd-search.failure .results li.state.failure { + display: block; +} + +#tsd-toolbar-links { + position: absolute; + top: 0; + right: 2rem; + height: 100%; + display: flex; + align-items: center; + justify-content: flex-end; +} +#tsd-toolbar-links a { + margin-left: 1.5rem; +} +#tsd-toolbar-links a:hover { + text-decoration: underline; +} + +.tsd-signature { + margin: 0 0 1rem 0; + padding: 1rem 0.5rem; + border: 1px solid var(--color-accent); + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; + font-size: 14px; + overflow-x: auto; +} + +.tsd-signature-keyword { + color: var(--color-ts-keyword); + font-weight: normal; +} + +.tsd-signature-symbol { + color: var(--color-text-aside); + font-weight: normal; +} + +.tsd-signature-type { + font-style: italic; + font-weight: normal; +} + +.tsd-signatures { + padding: 0; + margin: 0 0 1em 0; + list-style-type: none; +} +.tsd-signatures .tsd-signature { + margin: 0; + border-color: var(--color-accent); + border-width: 1px 0; + transition: background-color 0.1s; +} +.tsd-description .tsd-signatures .tsd-signature { + border-width: 1px; +} + +ul.tsd-parameter-list, +ul.tsd-type-parameter-list { + list-style: square; + margin: 0; + padding-left: 20px; +} +ul.tsd-parameter-list > li.tsd-parameter-signature, +ul.tsd-type-parameter-list > li.tsd-parameter-signature { + list-style: none; + margin-left: -20px; +} +ul.tsd-parameter-list h5, +ul.tsd-type-parameter-list h5 { + font-size: 16px; + margin: 1em 0 0.5em 0; +} +.tsd-sources { + margin-top: 1rem; + font-size: 0.875em; +} +.tsd-sources a { + color: var(--color-text-aside); + text-decoration: underline; +} +.tsd-sources ul { + list-style: none; + padding: 0; +} + +.tsd-page-toolbar { + position: sticky; + z-index: 1; + top: 0; + left: 0; + width: 100%; + color: var(--color-text); + background: var(--color-background-secondary); + border-bottom: 1px var(--color-accent) solid; + transition: transform 0.3s ease-in-out; +} +.tsd-page-toolbar a { + color: var(--color-text); + text-decoration: none; +} +.tsd-page-toolbar a.title { + font-weight: bold; +} +.tsd-page-toolbar a.title:hover { + text-decoration: underline; +} +.tsd-page-toolbar .tsd-toolbar-contents { + display: flex; + justify-content: space-between; + height: 2.5rem; + margin: 0 auto; +} +.tsd-page-toolbar .table-cell { + position: relative; + white-space: nowrap; + line-height: 40px; +} +.tsd-page-toolbar .table-cell:first-child { + width: 100%; +} +.tsd-page-toolbar .tsd-toolbar-icon { + box-sizing: border-box; + line-height: 0; + padding: 12px 0; +} + +.tsd-widget { + display: inline-block; + overflow: hidden; + opacity: 0.8; + height: 40px; + transition: + opacity 0.1s, + background-color 0.2s; + vertical-align: bottom; + cursor: pointer; +} +.tsd-widget:hover { + opacity: 0.9; +} +.tsd-widget.active { + opacity: 1; + background-color: var(--color-accent); +} +.tsd-widget.no-caption { + width: 40px; +} +.tsd-widget.no-caption:before { + margin: 0; +} + +.tsd-widget.options, +.tsd-widget.menu { + display: none; +} +input[type="checkbox"] + .tsd-widget:before { + background-position: -120px 0; +} +input[type="checkbox"]:checked + .tsd-widget:before { + background-position: -160px 0; +} + +img { + max-width: 100%; +} + +.tsd-anchor-icon { + display: inline-flex; + align-items: center; + margin-left: 0.5rem; + vertical-align: middle; + color: var(--color-text); +} + +.tsd-anchor-icon svg { + width: 1em; + height: 1em; + visibility: hidden; +} + +.tsd-anchor-link:hover > .tsd-anchor-icon svg { + visibility: visible; +} + +.deprecated { + text-decoration: line-through !important; +} + +.warning { + padding: 1rem; + color: var(--color-warning-text); + background: var(--color-background-warning); +} + +.tsd-kind-project { + color: var(--color-ts-project); +} +.tsd-kind-module { + color: var(--color-ts-module); +} +.tsd-kind-namespace { + color: var(--color-ts-namespace); +} +.tsd-kind-enum { + color: var(--color-ts-enum); +} +.tsd-kind-enum-member { + color: var(--color-ts-enum-member); +} +.tsd-kind-variable { + color: var(--color-ts-variable); +} +.tsd-kind-function { + color: var(--color-ts-function); +} +.tsd-kind-class { + color: var(--color-ts-class); +} +.tsd-kind-interface { + color: var(--color-ts-interface); +} +.tsd-kind-constructor { + color: var(--color-ts-constructor); +} +.tsd-kind-property { + color: var(--color-ts-property); +} +.tsd-kind-method { + color: var(--color-ts-method); +} +.tsd-kind-call-signature { + color: var(--color-ts-call-signature); +} +.tsd-kind-index-signature { + color: var(--color-ts-index-signature); +} +.tsd-kind-constructor-signature { + color: var(--color-ts-constructor-signature); +} +.tsd-kind-parameter { + color: var(--color-ts-parameter); +} +.tsd-kind-type-literal { + color: var(--color-ts-type-literal); +} +.tsd-kind-type-parameter { + color: var(--color-ts-type-parameter); +} +.tsd-kind-accessor { + color: var(--color-ts-accessor); +} +.tsd-kind-get-signature { + color: var(--color-ts-get-signature); +} +.tsd-kind-set-signature { + color: var(--color-ts-set-signature); +} +.tsd-kind-type-alias { + color: var(--color-ts-type-alias); +} + +/* if we have a kind icon, don't color the text by kind */ +.tsd-kind-icon ~ span { + color: var(--color-text); +} + +* { + scrollbar-width: thin; + scrollbar-color: var(--color-accent) var(--color-icon-background); +} + +*::-webkit-scrollbar { + width: 0.75rem; +} + +*::-webkit-scrollbar-track { + background: var(--color-icon-background); +} + +*::-webkit-scrollbar-thumb { + background-color: var(--color-accent); + border-radius: 999rem; + border: 0.25rem solid var(--color-icon-background); +} + +/* mobile */ +@media (max-width: 769px) { + .tsd-widget.options, + .tsd-widget.menu { + display: inline-block; + } + + .container-main { + display: flex; + } + html .col-content { + float: none; + max-width: 100%; + width: 100%; + } + html .col-sidebar { + position: fixed !important; + overflow-y: auto; + -webkit-overflow-scrolling: touch; + z-index: 1024; + top: 0 !important; + bottom: 0 !important; + left: auto !important; + right: 0 !important; + padding: 1.5rem 1.5rem 0 0; + width: 75vw; + visibility: hidden; + background-color: var(--color-background); + transform: translate(100%, 0); + } + html .col-sidebar > *:last-child { + padding-bottom: 20px; + } + html .overlay { + content: ""; + display: block; + position: fixed; + z-index: 1023; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.75); + visibility: hidden; + } + + .to-has-menu .overlay { + animation: fade-in 0.4s; + } + + .to-has-menu .col-sidebar { + animation: pop-in-from-right 0.4s; + } + + .from-has-menu .overlay { + animation: fade-out 0.4s; + } + + .from-has-menu .col-sidebar { + animation: pop-out-to-right 0.4s; + } + + .has-menu body { + overflow: hidden; + } + .has-menu .overlay { + visibility: visible; + } + .has-menu .col-sidebar { + visibility: visible; + transform: translate(0, 0); + display: flex; + flex-direction: column; + gap: 1.5rem; + max-height: 100vh; + padding: 1rem 2rem; + } + .has-menu .tsd-navigation { + max-height: 100%; + } +} + +/* one sidebar */ +@media (min-width: 770px) { + .container-main { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 2fr); + grid-template-areas: "sidebar content"; + margin: 2rem auto; + } + + .col-sidebar { + grid-area: sidebar; + } + .col-content { + grid-area: content; + padding: 0 1rem; + } +} +@media (min-width: 770px) and (max-width: 1399px) { + .col-sidebar { + max-height: calc(100vh - 2rem - 42px); + overflow: auto; + position: sticky; + top: 42px; + padding-top: 1rem; + } + .site-menu { + margin-top: 1rem; + } +} + +/* two sidebars */ +@media (min-width: 1200px) { + .container-main { + grid-template-columns: minmax(0, 1fr) minmax(0, 2.5fr) minmax(0, 20rem); + grid-template-areas: "sidebar content toc"; + } + + .col-sidebar { + display: contents; + } + + .page-menu { + grid-area: toc; + padding-left: 1rem; + } + .site-menu { + grid-area: sidebar; + } + + .site-menu { + margin-top: 1rem 0; + } + + .page-menu, + .site-menu { + max-height: calc(100vh - 2rem - 42px); + overflow: auto; + position: sticky; + top: 42px; + } +} diff --git a/docs/functions/vite_plugin_cp_src.default.html b/docs/functions/vite_plugin_cp_src.default.html new file mode 100644 index 0000000..dc49925 --- /dev/null +++ b/docs/functions/vite_plugin_cp_src.default.html @@ -0,0 +1,4 @@ +default | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/functions/vite_plugin_external_src.default.html b/docs/functions/vite_plugin_external_src.default.html new file mode 100644 index 0000000..865431b --- /dev/null +++ b/docs/functions/vite_plugin_external_src.default.html @@ -0,0 +1,4 @@ +default | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/functions/vite_plugin_hook_use_src.default.html b/docs/functions/vite_plugin_hook_use_src.default.html new file mode 100644 index 0000000..71c7c9a --- /dev/null +++ b/docs/functions/vite_plugin_hook_use_src.default.html @@ -0,0 +1,3 @@ +default | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/functions/vite_plugin_include_css_src.default.html b/docs/functions/vite_plugin_include_css_src.default.html new file mode 100644 index 0000000..6f9a1a4 --- /dev/null +++ b/docs/functions/vite_plugin_include_css_src.default.html @@ -0,0 +1,3 @@ +default | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/functions/vite_plugin_mock_data_src.default.html b/docs/functions/vite_plugin_mock_data_src.default.html new file mode 100644 index 0000000..6bb0f95 --- /dev/null +++ b/docs/functions/vite_plugin_mock_data_src.default.html @@ -0,0 +1,4 @@ +default | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/functions/vite_plugin_reverse_proxy_src.default.html b/docs/functions/vite_plugin_reverse_proxy_src.default.html new file mode 100644 index 0000000..9783cd0 --- /dev/null +++ b/docs/functions/vite_plugin_reverse_proxy_src.default.html @@ -0,0 +1,4 @@ +default | vite-plugins
  • Makes the script to be served with the text/javascript MIME type instead of module MIME type.

    +

    Parameters

    Returns {
        name: string;
        config(config): void;
        configResolved(config): void;
        load(id): undefined | string;
    }

    a vite plugin

    +

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..c83ac45 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,28 @@ +vite-plugins

vite-plugins

+

Some custom plugins for vitejs.

+
+ + + + + + + + + + + + + + + + + + + + + + + +
PackagesDescription
vite-plugin-cpCopy files after building bundles.
vite-plugin-externalProvides a way of excluding dependencies from the runtime code and output bundles.
vite-plugin-mock-dataProvides a simple way to mock data.
vite-plugin-reverse-proxyMakes the script to be served with the text/javascript MIME type instead of module MIME type.
+

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_cp_src.Options.html b/docs/interfaces/vite_plugin_cp_src.Options.html new file mode 100644 index 0000000..cfa3867 --- /dev/null +++ b/docs/interfaces/vite_plugin_cp_src.Options.html @@ -0,0 +1,11 @@ +Options | vite-plugins
interface Options {
    cwd?: string;
    enforce?: "pre" | "post";
    globbyOptions?: Options;
    hook?: string;
    targets: Target[];
}

Properties

cwd?: string

Default process.cwd(), The current working directory in which to search.

+
enforce?: "pre" | "post"

It may be needed to enforce the order of the plugin or only apply at build time.

+
globbyOptions?: Options

Options for globby. See more at https://github.com/sindresorhus/globby#options

+
hook?: string

Default 'closeBundle', vite hook the plugin should use.

+
targets: Target[]

Array of targets to copy. A target is an object with properties

+

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_cp_src.Target.html b/docs/interfaces/vite_plugin_cp_src.Target.html new file mode 100644 index 0000000..a09f8d6 --- /dev/null +++ b/docs/interfaces/vite_plugin_cp_src.Target.html @@ -0,0 +1,13 @@ +Target | vite-plugins
interface Target {
    dest: string;
    flatten?: boolean;
    globbyOptions?: Options;
    rename?: string | ((name) => string);
    src: string | string[];
    transform?: ((buf, matchedPath) => string | Buffer | Promise<string | Buffer>);
}

Properties

dest: string

One or more destinations where to copy.

+
flatten?: boolean

Remove the directory structure of copied files.

+
globbyOptions?: Options

Options for globby. See more at https://github.com/sindresorhus/globby#options

+
rename?: string | ((name) => string)

Rename the file after copying.

+

Type declaration

    • (name): string
    • Parameters

      • name: string

      Returns string

src: string | string[]

Path or glob of what to copy.

+
transform?: ((buf, matchedPath) => string | Buffer | Promise<string | Buffer>)

Type declaration

    • (buf, matchedPath): string | Buffer | Promise<string | Buffer>
    • Transform the file before copying.

      +

      Parameters

      • buf: Buffer
      • matchedPath: string

      Returns string | Buffer | Promise<string | Buffer>

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_external_src.BasicOptions.html b/docs/interfaces/vite_plugin_external_src.BasicOptions.html new file mode 100644 index 0000000..b6ee9a7 --- /dev/null +++ b/docs/interfaces/vite_plugin_external_src.BasicOptions.html @@ -0,0 +1,6 @@ +BasicOptions | vite-plugins
interface BasicOptions {
    cacheDir?: string;
    cwd?: string;
    externals: Record<string, any>;
}

Hierarchy

Properties

Properties

cacheDir?: string

Default

${cwd}/node_modules/.vite_external

+
cwd?: string

Default

process.cwd()

+
externals: Record<string, any>

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_external_src.Options.html b/docs/interfaces/vite_plugin_external_src.Options.html new file mode 100644 index 0000000..6241cf6 --- /dev/null +++ b/docs/interfaces/vite_plugin_external_src.Options.html @@ -0,0 +1,12 @@ +Options | vite-plugins
interface Options {
    cacheDir?: string;
    cwd?: string;
    devMode?: string;
    development?: BasicOptions;
    enforce?: "pre" | "post";
    externals: Record<string, any>;
    production?: BasicOptions;
    [mode: string]: BasicOptions | any;
}

Hierarchy

Indexable

[mode: string]: BasicOptions | any

Properties

cacheDir?: string

Default

${cwd}/node_modules/.vite_external

+
cwd?: string

Default

process.cwd()

+
devMode?: string
development?: BasicOptions

development mode options

+
enforce?: "pre" | "post"
externals: Record<string, any>
production?: BasicOptions

production mode options

+

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_mock_data_src.HandleRoute.html b/docs/interfaces/vite_plugin_mock_data_src.HandleRoute.html new file mode 100644 index 0000000..cfe6914 --- /dev/null +++ b/docs/interfaces/vite_plugin_mock_data_src.HandleRoute.html @@ -0,0 +1,5 @@ +HandleRoute | vite-plugins
interface HandleRoute {
    file?: string;
    handler?: any;
    options?: RouteOptions;
    store?: any;
}

Properties

Properties

file?: string
handler?: any
options?: RouteOptions
store?: any

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_mock_data_src.Options.html b/docs/interfaces/vite_plugin_mock_data_src.Options.html new file mode 100644 index 0000000..7f69ee3 --- /dev/null +++ b/docs/interfaces/vite_plugin_mock_data_src.Options.html @@ -0,0 +1,15 @@ +Options | vite-plugins
interface Options {
    cwd?: string;
    isAfter?: boolean;
    mockAssetsDir?: string;
    mockRouterOptions?: Config<V1> | Config<V2>;
    mockRoutes?: RouteConfig | RouteConfig[];
    mockRoutesDir?: string;
}

Properties

cwd?: string

The directory to serve files from.

+

Default

process.cwd()

+
isAfter?: boolean

If true, these mock routes is matched after internal middlewares are installed.

+

Default

false

+
mockAssetsDir?: string

Specify the directory to define mock assets.

+
mockRouterOptions?: Config<V1> | Config<V2>

Initial options of find-my-way. see more at https://github.com/delvedor/find-my-way#findmywayoptions

+
mockRoutes?: RouteConfig | RouteConfig[]

Initial list of mock routes that should be added to the dev server.

+
mockRoutesDir?: string

Specify the directory to define mock routes that should be added to the dev server.

+

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_mock_data_src.RouteConfig.html b/docs/interfaces/vite_plugin_mock_data_src.RouteConfig.html new file mode 100644 index 0000000..ab2db33 --- /dev/null +++ b/docs/interfaces/vite_plugin_mock_data_src.RouteConfig.html @@ -0,0 +1 @@ +RouteConfig | vite-plugins
interface RouteConfig {
    [route: string]: string | Handler<HTTPVersion.V1> | HandleRoute;
}

Indexable

[route: string]: string | Handler<HTTPVersion.V1> | HandleRoute

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/vite_plugin_reverse_proxy_src.Options.html b/docs/interfaces/vite_plugin_reverse_proxy_src.Options.html new file mode 100644 index 0000000..3694036 --- /dev/null +++ b/docs/interfaces/vite_plugin_reverse_proxy_src.Options.html @@ -0,0 +1,3 @@ +Options | vite-plugins
interface Options {
    preambleCode?: string;
    targets?: Record<string, string>;
}

Properties

Properties

preambleCode?: string
targets?: Record<string, string>

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_cp_src.html b/docs/modules/vite_plugin_cp_src.html new file mode 100644 index 0000000..717623a --- /dev/null +++ b/docs/modules/vite_plugin_cp_src.html @@ -0,0 +1,4 @@ +vite-plugin-cp/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_external_src.html b/docs/modules/vite_plugin_external_src.html new file mode 100644 index 0000000..0a8ea89 --- /dev/null +++ b/docs/modules/vite_plugin_external_src.html @@ -0,0 +1,4 @@ +vite-plugin-external/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_hook_use_src.html b/docs/modules/vite_plugin_hook_use_src.html new file mode 100644 index 0000000..eede07f --- /dev/null +++ b/docs/modules/vite_plugin_hook_use_src.html @@ -0,0 +1,2 @@ +vite-plugin-hook-use/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_include_css_src.html b/docs/modules/vite_plugin_include_css_src.html new file mode 100644 index 0000000..1eceb98 --- /dev/null +++ b/docs/modules/vite_plugin_include_css_src.html @@ -0,0 +1,2 @@ +vite-plugin-include-css/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_mock_data_src.html b/docs/modules/vite_plugin_mock_data_src.html new file mode 100644 index 0000000..656701d --- /dev/null +++ b/docs/modules/vite_plugin_mock_data_src.html @@ -0,0 +1,5 @@ +vite-plugin-mock-data/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/modules/vite_plugin_reverse_proxy_src.html b/docs/modules/vite_plugin_reverse_proxy_src.html new file mode 100644 index 0000000..ea0d9fb --- /dev/null +++ b/docs/modules/vite_plugin_reverse_proxy_src.html @@ -0,0 +1,3 @@ +vite-plugin-reverse-proxy/src | vite-plugins

Generated using TypeDoc

\ No newline at end of file diff --git a/examples/demo/babel.config.js b/examples/demo/babel.config.js deleted file mode 100644 index 8d1e079..0000000 --- a/examples/demo/babel.config.js +++ /dev/null @@ -1,21 +0,0 @@ -module.exports = { - presets: [ - '@babel/preset-react', - ['@babel/preset-env', { loose: true }] - ], - plugins: [ - ['transform-react-remove-prop-types', { - mode: 'remove', - removeImport: true - }], // 移除 PropTypes - ['@babel/plugin-transform-runtime', { - corejs: false, - regenerator: false - }], - '@babel/plugin-proposal-export-default-from', // export v from 'mod'; - ['@babel/plugin-proposal-decorators', { legacy: true }], // @annotation - '@babel/plugin-syntax-import-meta', // import.meta - 'lodash', // import _ from 'lodash'; _.map() -> import _map from 'lodash/map'; _map() - 'jsx-advanced' // jsx 扩展指令 - ] -}; diff --git a/examples/demo/index.html b/examples/demo/index.html deleted file mode 100644 index 25b18c2..0000000 --- a/examples/demo/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - 云端控制台 - - - - - - - - -
- - - - \ No newline at end of file diff --git a/examples/demo/jsconfig.json b/examples/demo/jsconfig.json deleted file mode 100644 index dc3a533..0000000 --- a/examples/demo/jsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "experimentalDecorators": true, - "baseUrl": ".", - "jsx": "react", - "paths": { - "@/*": ["./src/*"] - } - } -} diff --git a/examples/demo/package.json b/examples/demo/package.json deleted file mode 100644 index 5ebf639..0000000 --- a/examples/demo/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "demo", - "version": "1.0.0", - "private": true, - "scripts": { - "dev": "vite", - "build": "vite build", - "serve": "vite preview", - "eslint": "eslint --fix --ext .js,.jsx ./" - }, - "dependencies": { - "@alicloud/console-components": "^1.3.0", - "@babel/plugin-proposal-decorators": "^7.14.5", - "@babel/plugin-proposal-export-default-from": "^7.14.5", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-transform-runtime": "^7.14.5", - "@babel/preset-env": "^7.14.9", - "@babel/preset-react": "^7.14.5", - "@babel/runtime": "^7.14.8", - "@linkdesign/components": "^1.3.3", - "@rollup/plugin-babel": "^5.3.0", - "babel-plugin-jsx-advanced": "^1.1.5", - "babel-plugin-lodash": "^3.3.4", - "babel-plugin-transform-react-remove-prop-types": "^0.4.24", - "babel-runtime-jsx-advanced-helper": "^1.0.0", - "celia": "^8.0.4", - "fast-classnames": "^1.0.0", - "history": "^4.10.1", - "jest": "^27.0.3", - "lodash": "^4.17.21", - "react-route-view": "^1.0.0", - "sass": "^1.35.2", - "vite": "^2.4.3" - }, - "devDependencies": { - "@vitejs/plugin-react-refresh": "^1.3.1", - "moment": "^2.29.1", - "react": "^16.14.0", - "react-dom": "^16.14.0", - "react-router": "^5.2.0" - }, - "husky": { - "hooks": { - "pre-commit": "lint-staged", - "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS" - } - }, - "lint-staged": { - "*.{js,jsx}": [ - "eslint --fix", - "git add" - ] - } -} \ No newline at end of file diff --git a/examples/demo/public/index.html b/examples/demo/public/index.html deleted file mode 100644 index 5f21df1..0000000 --- a/examples/demo/public/index.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - 本地控制台 - - - -
- - - diff --git a/examples/demo/src/common/gloading.js b/examples/demo/src/common/gloading.js deleted file mode 100644 index b2ab8e3..0000000 --- a/examples/demo/src/common/gloading.js +++ /dev/null @@ -1,17 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import { Loading } from '@alicloud/console-components'; - -const wrap = document.body.appendChild(document.createElement('div')); - -export function show() { - ReactDOM.render(( - - ), wrap); -} - -export function hide() { - ReactDOM.render(( - - ), wrap); -} diff --git a/examples/demo/src/common/http.js b/examples/demo/src/common/http.js deleted file mode 100644 index a777962..0000000 --- a/examples/demo/src/common/http.js +++ /dev/null @@ -1,14 +0,0 @@ -import { history } from '@/config/routes'; -import { isActive, isLogin } from '@/common/user'; -import { sleep } from 'celia'; - -export default function () { - return sleep(1000).then(() => { - if (!isLogin()) { - history.push('/login'); - } - else if (!isActive()) { - history.push('/inactive'); - } - }); -} diff --git a/examples/demo/src/common/router.js b/examples/demo/src/common/router.js deleted file mode 100644 index bfdec13..0000000 --- a/examples/demo/src/common/router.js +++ /dev/null @@ -1,132 +0,0 @@ -import { createElement } from 'react'; -import { Router as ReactRouter, Redirect, Route, Switch } from 'react-router'; -import { createHashHistory, createBrowserHistory, createMemoryHistory } from 'history'; -import { objectWithoutProperties, pathJoin } from 'celia'; - -function createName() { - return Math.random().toString(36).slice(2); -} - -function createHistoryBy(mode, historyOptions) { - switch (mode) { - case 'hash': - return createHashHistory(historyOptions); - case 'history': - return createBrowserHistory(historyOptions); - case 'memory': - return createMemoryHistory(historyOptions); - default: - throw new Error(`invalid mode: ${mode}`); - } -} - -function createRoute( - parentName, - parentPath, - route, - routeConfigCache, -) { - // 具名路由 - let name = route.name || route.key; - if (!name) { - name = `${parentName}.${createName()}`; - route.name = name; - } - - // 解析了之后直接执行 - const routeCache = routeConfigCache[name]; - if (routeCache) { - return routeCache.render(routeCache.props); - } - - let { path } = route; - if (!path) { - throw new Error(`Missing path in named route ${name}`); - } - path = pathJoin(parentPath || '', path); - - const redirect = route.redirect || route.to; - if (redirect) { - const props = { - key: name, - exact: true, - from: path, - to: redirect - }; - const render = function (props) { - return createElement(Redirect, props); // 跳转路由 - }; - routeConfigCache[name] = { props, render }; - return render(props); - } - - const routeConfig = objectWithoutProperties(route, [ - 'to', - 'redirect', - 'component', - 'render', - 'children' - ]); - routeConfig.path = path; - routeConfig.key = name; - - const { component, children, render } = route; - - routeConfig.render = function (cprops) { - cprops.route = routeConfig; - return render ? render(cprops) : createElement(component, cprops); - }; - - const routeRender = function (props) { - return !children || !children.length - ? createElement(Route, props) - : createElement( - component, - { key: `${name}-component`, route: props }, - createSwitch(name, path, children, routeConfigCache) - ); // 如果有子路由,先创建对应的组件,再递归创建 Route - }; - routeConfigCache[name] = { props: routeConfig, render: routeRender }; - return routeRender(routeConfig); -} - -function createSwitch(parentName, parentPath, routes, routeConfigCache) { - return createElement( - Switch, - null, - routes.map((route) => { - return createRoute( - parentName, - parentPath, - route, - routeConfigCache - ); - }) - ); -} - -export function create({ - mode, - routes, - ...historyOptions -}) { - const history = createHistoryBy(mode, historyOptions); - const routeConfigCache = {}; - - return { - history, - - Router() { - return createElement( - ReactRouter, - { history }, - createSwitch( - 'router', - '', - routes, - routeConfigCache - ) - ); - } - }; -} diff --git a/examples/demo/src/common/user.js b/examples/demo/src/common/user.js deleted file mode 100644 index ebebdb6..0000000 --- a/examples/demo/src/common/user.js +++ /dev/null @@ -1,15 +0,0 @@ -export function isLogin() { - return !!sessionStorage.getItem('token'); -} - -export function isActive() { - return !!sessionStorage.getItem('active'); -} - -export function stashActiveFlag(flag) { - sessionStorage.setItem('active', flag); -} - -export function stashToken(token) { - sessionStorage.setItem('token', token); -} diff --git a/examples/demo/src/config/aside.js b/examples/demo/src/config/aside.js deleted file mode 100644 index f389b44..0000000 --- a/examples/demo/src/config/aside.js +++ /dev/null @@ -1,28 +0,0 @@ -import { history } from './routes'; - -export default { - header: '本地控制台', - onSelect(selectedKeys) { - history.push(selectedKeys[0]); - }, - dataSource: [{ - label: '引导页', - key: '/guide' - }, - { - label: '设备管理', - key: '/devices' - }, - { - label: '任务管理', - key: '/tasks' - }, - { - label: '监控管理', - key: '/monitor' - }, - { - label: '系统管理', - key: '/system' - }] -}; diff --git a/examples/demo/src/config/routes.js b/examples/demo/src/config/routes.js deleted file mode 100644 index c0beca2..0000000 --- a/examples/demo/src/config/routes.js +++ /dev/null @@ -1,117 +0,0 @@ -import { create as createRouteView } from 'react-route-view'; -import { create } from '../common/router'; -import BasicLayout from '../layouts/BasicLayout'; -import Devices from '../pages/devices'; -import Guide from '../pages/guide'; -import Monitor from '../pages/monitor'; -import System from '../pages/system'; -import Tasks from '../pages/tasks'; -import Login from '../pages/login'; -import Inactive from '../pages/inactive'; -import { isActive, isLogin } from '@/common/user'; -// import { show } from '@/common/gloading'; - -const { connect } = createRouteView({ - beforeEach(to, from, next) { - console.info('beforeEach', 'to', to, 'from', from); - - const { name } = to; - if (!isLogin()) { - if (name !== 'login') { - to.history.push('/login'); - return; - } - } - else if (name === 'login') { - to.history.push('/'); - return; - } - else if (!isActive()) { - if (name !== 'inactive') { - to.history.push('/inactive'); - return; - } - } - else if (name === 'inactive') { - to.history.push('/'); - return; - } - - next(); - } -}); - -const { Router, history } = create({ - mode: 'hash', - routes: [ - { - name: 'login', - path: '/login', - exact: true, - component: connect(Login) - }, - { - name: 'inactive', - path: '/inactive', - exact: true, - component: connect(Inactive) - }, - { - path: '/', - component: BasicLayout, - children: [ - { - path: '/', - redirect: '/guide' - }, - { - path: '/guide', - render: connect(Guide, { - beforeEnter(to, from, next) { - console.info('beforeEnter guide'); - next(); - } - }) - }, - { - path: '/devices', - render: connect(Devices, { - beforeEnter(to, from, next) { - console.info('beforeEnter devices'); - next(); - } - }) - }, - { - path: '/tasks', - render: connect(Tasks, { - beforeEnter(to, from, next) { - console.info('beforeEnter tasks'); - next('/guide'); - } - }) - }, - { - path: '/monitor', - render: connect(Monitor, { - beforeEnter(to, from, next) { - console.info('beforeEnter monitor'); - next(); - } - }) - }, - { - path: '/system', - render: connect(System, { - beforeEnter(to, from, next) { - console.info('beforeEnter system'); - next(); - } - }) - } - ] - } - ] -}); - -export { Router, history }; diff --git a/examples/demo/src/index.jsx b/examples/demo/src/index.jsx deleted file mode 100644 index b89fba7..0000000 --- a/examples/demo/src/index.jsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import { Router } from './config/routes'; - -const BUNDLE = document.getElementById('bundle'); -if (!BUNDLE) { - throw new Error('当前页面不存在
节点.'); -} - -ReactDOM.render( - ( - - ), - BUNDLE, -); diff --git a/examples/demo/src/layouts/BasicLayout/index.jsx b/examples/demo/src/layouts/BasicLayout/index.jsx deleted file mode 100644 index a9ac955..0000000 --- a/examples/demo/src/layouts/BasicLayout/index.jsx +++ /dev/null @@ -1,28 +0,0 @@ -import styles from './index.module.scss'; -import React from 'react'; -import { Layout, SilderNav } from '@linkdesign/components'; -import aside from '@/config/aside'; - -const Panel = Layout.panel; - -function BasicLayout({ children, location }) { - aside.activeKey = location.pathname; - - return ( - <> - -
- - - {children} - -
- - ); -} - -export default BasicLayout; diff --git a/examples/demo/src/layouts/BasicLayout/index.module.scss b/examples/demo/src/layouts/BasicLayout/index.module.scss deleted file mode 100644 index ba41a77..0000000 --- a/examples/demo/src/layouts/BasicLayout/index.module.scss +++ /dev/null @@ -1,35 +0,0 @@ -$header-height: 50px; - -.header { - height: $header-height; - line-height: $header-height; - background-color: #fff; - position: fixed; - top: 0; - left: 0; - width: 100%; - box-shadow: 0 1px 4px 0 rgba(0,0,0,.08); - z-index: 200; - - & > a { - margin-left: 24px; - } - .logo { - width: 88px; - height: 100%; - display: inline-block; - vertical-align: middle; - font-size: 32px; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - } -} - -.body { - display: flex; - margin-top: $header-height; - height: calc(100vh - #{$header-height}); -} - -.main { - width: 100%; -} \ No newline at end of file diff --git a/examples/demo/src/pages/devices/index.jsx b/examples/demo/src/pages/devices/index.jsx deleted file mode 100644 index d4065d2..0000000 --- a/examples/demo/src/pages/devices/index.jsx +++ /dev/null @@ -1,174 +0,0 @@ -import React, { Component } from 'react'; -import { Icon, Switch } from '@alicloud/console-components'; -import { FilterGroup, Table, Layout } from '@linkdesign/components'; -import { getDevices } from '@/services/devices'; - -const LayoutContainer = Layout.container; - -function Status(status) { - const state = status ? { type: 'select', color: '#1E8E3E' } : { type: 'warning', color: '#FF0000' }; - - return ( -
- - {status ? '已绑定' : '未绑定'} -
- ); -} -export default class Device extends Component { - constructor(props) { - super(props); - this.state = { - keyword: '1' - }; - } - - componentDidMount() { - console.info('componentDidMount devices'); - } - - render() { - console.info('render devices'); - return ( - - { - console.info('创建项目'); - } - } - }, - { - type: 'button', - name: 'second', - label: '次要按钮', - props: { - onClick: (e) => { - console.info('刷新按钮', e); - } - } - }, - { - type: 'input', - name: 'inputContext', - label: '请输入搜索内容', - props: { - hasClear: true, - onChange: (values) => { - console.info('我的输入', values); - } - } - } - ]} - /> - getDevices(param.PageNo, param.PageSize).then((n) => ({ - dataSource: n.list, - total: 40 - })) - } - extraFilter={{ Name: this.state.keyword }} - columns={[ - { - title: '产品名称', - dataIndex: 'id' - }, - { - title: 'ProductKey', - dataIndex: 'ProductKey' - }, - { - title: '节点类型', - dataIndex: 'NodeType' - }, - { - title: '节点状态', - dataIndex: 'Status', - cell: (value) => () - }, - { - title: '设备起停', - dataIndex: 'f_value', - cell: (value, index) => () - }, - { - title: '添加时间', - dataIndex: 'UpdateTime' - } - ]} - actions={{ - title: '操作集合', - width: 224, - max: 3, - maxText: '更多', - buttons: [ - { - content: '删除', - onClick: (e, rawData) => { - console.info('删除', e, rawData); - } - }, - { - content: '添加', - onClick: (e, rawData) => { - console.info('添加', e, rawData); - } - }, - { - content: '测试' - }, - { - content: '更新', - onClick: (e, rawData) => { - console.info('更新', e, rawData); - } - }, - { - content: '回退' - } - ] - }} - batchActionContent={[ - { - size: 'small', - onClick: (v) => { - console.info('被选中的', v); - // eslint-disable-next-line no-alert - alert('已删除'); - }, - name: '批量删除' - } - ]} - rowSelection={{}} - locale={{ - prev: '上一页', - next: '下一页', - goTo: '到第', - page: '页', - go: '确定', - pageSize: '每页显示', - total: (value) => { - return `共有${value}页`; - } - }} - /> - - ); - } -} diff --git a/examples/demo/src/pages/guide/index.jsx b/examples/demo/src/pages/guide/index.jsx deleted file mode 100644 index 1ddc511..0000000 --- a/examples/demo/src/pages/guide/index.jsx +++ /dev/null @@ -1,28 +0,0 @@ -import React, { Component } from 'react'; -import { Layout } from '@linkdesign/components'; - -const LayoutContainer = Layout.container; -export default class extends Component { - componentDidMount() { - console.info('componentDidMount 引导页'); - } - - render() { - console.info('render 引导页'); - - return ( - - ); - } -} diff --git a/examples/demo/src/pages/inactive/index.jsx b/examples/demo/src/pages/inactive/index.jsx deleted file mode 100644 index 73e01aa..0000000 --- a/examples/demo/src/pages/inactive/index.jsx +++ /dev/null @@ -1,78 +0,0 @@ -/* eslint-disable max-len */ -import styles from './index.module.scss'; -import React from 'react'; -import { Button, Icon, Message } from '@alicloud/console-components'; -import { history } from '../../config/routes'; -import { stashActiveFlag } from '@/common/user'; - -const productAdvantages = [ - { - img: 'https://gw.alicdn.com/imgextra/i3/O1CN01xikAkX1WQeumZ72ZI_!!6000000002783-55-tps-48-48.svg', - h: '优势一', - p: '优势一内容。' - }, - { - img: 'https://img.alicdn.com/imgextra/i1/O1CN01klOrLq1C0HnFwCBBQ_!!6000000000018-55-tps-48-48.svg', - h: '优势二', - p: '优势二内容。' - }, - { - img: 'https://img.alicdn.com/imgextra/i1/O1CN01bDSqrU1sUhxo0EJJu_!!6000000005770-55-tps-48-48.svg', - h: '优势三I', - p: '优势三内容。' - }, - { - img: 'https://img.alicdn.com/imgextra/i2/O1CN01u76C1P1TFGDBqc8Tm_!!6000000002352-55-tps-48-48.svg', - h: '优势四', - p: '优势四内容。' - } -]; - -export default function Inactive() { - const onActive = () => { - stashActiveFlag(1); - history.push('/'); - Message.success('开通服务成功'); - }; - - return ( -
-
-
- -
-
-

某产品服务

-

- 某产品服务介绍 - - 了解详情  - - -

- -
-
-
-
-

产品优势

-
    -
  • - - - - - - -

    {advantage.h}

    -

    {advantage.p}

    -
    -
    -
    -
  • -
-
-
-
- ); -} diff --git a/examples/demo/src/pages/inactive/index.module.scss b/examples/demo/src/pages/inactive/index.module.scss deleted file mode 100644 index cbec95d..0000000 --- a/examples/demo/src/pages/inactive/index.module.scss +++ /dev/null @@ -1,185 +0,0 @@ -.inactive-page { - margin: 0 -24px -18px; - display: flex; - flex-direction: column; - height: 100%; - min-width: 1024px; - - :global { - a:hover { - text-decoration: none; - } - } -} - -.introduce { - height: 224px; - flex-shrink: 0; - max-width: 1024px; - margin: 60px auto 0 auto; - display: flex; - flex-direction: row; - - &-wrapped-img { - flex: 1 0 220px; - - img { - width: 220px; - } - } - - &-info { - margin-left: 32px; - - &-title { - margin: 0; - text-align: left; - line-height: 36px; - font-size: 28px; - color: #111111; - height: 36px; - } - - &-desc { - margin: 8px 0 24px 0; - text-align: left; - line-height: 20px; - font-size: 12px; - color: #333333; - } - } -} - -.grey-area { - background-color: #fafafa; - - h3 { - height: 22px; - line-height: 22px; - color: #333; - margin: 40px 0 16px 0; - font-size: 14px; - font-weight: 700; - } -} - -.product-advantages { - max-width: 1024px; - margin: 0 auto; - ul { - margin: -8px; - letter-spacing: -0.31em; - *letter-spacing: normal; - word-spacing: -0.43em; - - li { - width: 50%; - display: inline-block; - zoom: 1; - letter-spacing: normal; - word-spacing: normal; - vertical-align: top; - } - } - - &-u-wrapped { - padding: 8px; - display: block; - width: 100%; - } - - &-u { - // margin: 8px; - padding: 0 16px 0 0; - display: inline-block; - vertical-align: top; - width: 100%; - // height: 102px; - box-shadow: 0 1px 4px 0 rgba(0,0,0,0.13); - background-color: #FFFFFF; - // transition: all .2s ease; - - // &:hover { - // transform: scale(1.04); - // } - - $img-width: 80px; - &-wrapped-img { - display: block; - width: $img-width; - float: left; - - img { - display: block; - margin: 16px auto 0 auto; - } - } - - &-info { - display: block; - margin-left: $img-width; - - h4 { - margin: 16px 0 0 0; - height: 22px; - line-height: 22px; - color: #333333; - font-size: 14px; - font-weight: 700; - } - - p { - margin: 8px 0 16px 0; - line-height: 20px; - color: #555555; - min-height: 40px; - } - } - } -} - -.related-links { - max-width: 1024px; - margin: 0 auto 53px auto; - - ul { - margin: -4px; - padding: 0; - letter-spacing: -0.31em; - *letter-spacing: normal; - word-spacing: -0.43em; - // background-color: #FFFFFF; - - li { - width: 33.3333%; - display: inline-block; - zoom: 1; - letter-spacing: normal; - word-spacing: normal; - vertical-align: top; - } - } - - &-u { - // margin: 4px 0 4px 28px; - margin: 0 4px; - display: block; - height: 20px; - line-height: 20px; - color: #333333; - // &:before { - // content: ''; - // display: block; - // width: 4px; - // height: 4px; - // background-color: #333333; - // position: relative; - // left: -12px; - // top: 12px - // } - } -} - -.empty { - height: 100%; -} diff --git a/examples/demo/src/pages/login/index.jsx b/examples/demo/src/pages/login/index.jsx deleted file mode 100644 index 02801f3..0000000 --- a/examples/demo/src/pages/login/index.jsx +++ /dev/null @@ -1,106 +0,0 @@ -import styles from './index.module.scss'; -import React, { useState, useCallback } from 'react'; -import { Input, Form, Message } from '@alicloud/console-components'; -import { history } from '@/config/routes'; -import { stashToken } from '@/common/user'; -import bg from './login-bg.jpg'; - -const FormItem = Form.Item; - -function useMain() { - const [state, setState] = useState({ - loading: false, - errorMessage: '', - value: { - username: 'admin', - password: '' - } - }); - - const formChange = useCallback((formValue) => { - setState((prev) => { - return { - ...prev, - value: { ...prev.value, ...formValue } - }; - }); - }, [setState]); - - const handleSubmit = useCallback((values, errors) => { - if (errors) { - return; - } - setState((prev) => ({ ...prev, loading: true })); - setTimeout(() => { - setState((prev) => ({ ...prev, loading: false })); - stashToken(123456); - history.push('/guide'); - }, 200); - }, [setState]); - - return { - state, - formChange, - handleSubmit - }; -} - -function LoginForm() { - const { state, formChange, handleSubmit } = useMain(); - const { value, errorMessage, loading } = state; - - return ( -

-
-

管理员登录

-
- {errorMessage} -
-
- - - - - - {loading ? '登录中...' : '登录'} - - - -
-

- ); -} - -export default function () { - - return ( -
-
- LOGO -
-
-

欢迎访问

-

本地控制台

-
-
- -
-
- ); -} diff --git a/examples/demo/src/pages/login/index.module.scss b/examples/demo/src/pages/login/index.module.scss deleted file mode 100644 index 3c743bc..0000000 --- a/examples/demo/src/pages/login/index.module.scss +++ /dev/null @@ -1,106 +0,0 @@ -.login-layout { - position: relative; - width: 100%; - background: #ffffff; -} - -.header { - line-height: 48px; - height: 48px; - padding: 0 16px; - - .logo { - width: 88px; - height: 100%; - display: inline-block; - vertical-align: middle; - font-size: 32px; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - } -} - -.content { - background-position: center center; - background-repeat: no-repeat; - background-size: cover; - min-height: calc(100vh - 48px); -} - -.aside { - position: absolute; - top: 60px + 48px; - left: 60px; - - h2, p { - margin: 0; - padding: 0; - } - - h2 { - height: 40px; - line-height: 40px; - color: #ffffff; - font-size: 32px; - font-weight: 400; - } - - p { - height: 40px; - font-size: 24px; - color: #FFFFFF; - line-height: 40px; - } -} - -.login-frame { - background-color: #ffffff; - width: 380px; - // height: 230px; - position: absolute; - top: 186px; - left: 50%; - transform: translateX(-50%); -} - -.login-box { - padding: 22px 30px 36px 30px; - & > h3 { - margin: 0; - font-size: 18px; - color: #393C42; - line-height: 25px; - height: 25px; - color: #393C42; - } - :global { - .next-form-item { - margin-bottom: 18px; - } - } -} - -.login-input { - & > input { - height: 40px !important; - line-height: 40px; - } -} - -.login-error { - padding: 20px 0 18px 0; - &.blank { - padding: 31px 0 0 0; - } - :global { - .next-message { - padding: 5px !important; - } - } -} - -.login-submit { - height: 42px !important; - line-height: 40px !important; - width: 100%; - font-size: 16px !important; -} diff --git a/examples/demo/src/pages/login/login-bg.jpg b/examples/demo/src/pages/login/login-bg.jpg deleted file mode 100644 index 17125fc..0000000 Binary files a/examples/demo/src/pages/login/login-bg.jpg and /dev/null differ diff --git a/examples/demo/src/pages/monitor/index.jsx b/examples/demo/src/pages/monitor/index.jsx deleted file mode 100644 index e3d3ee7..0000000 --- a/examples/demo/src/pages/monitor/index.jsx +++ /dev/null @@ -1,28 +0,0 @@ -import React, { Component } from 'react'; -import { Layout } from '@linkdesign/components'; - -const LayoutContainer = Layout.container; -export default class extends Component { - componentDidMount() { - console.info('componentDidMount 监控管理'); - } - - render() { - console.info('render 监控管理'); - - return ( - - ); - } -} diff --git a/examples/demo/src/pages/system/index.jsx b/examples/demo/src/pages/system/index.jsx deleted file mode 100644 index c4115d5..0000000 --- a/examples/demo/src/pages/system/index.jsx +++ /dev/null @@ -1,28 +0,0 @@ -import React, { Component } from 'react'; -import { Layout } from '@linkdesign/components'; - -const LayoutContainer = Layout.container; -export default class extends Component { - componentDidMount() { - console.info('componentDidMount 系统管理'); - } - - render() { - console.info('render 系统管理'); - - return ( - - ); - } -} diff --git a/examples/demo/src/pages/tasks/index.jsx b/examples/demo/src/pages/tasks/index.jsx deleted file mode 100644 index c9d3100..0000000 --- a/examples/demo/src/pages/tasks/index.jsx +++ /dev/null @@ -1,28 +0,0 @@ -import React, { Component } from 'react'; -import { Layout } from '@linkdesign/components'; - -const LayoutContainer = Layout.container; -export default class extends Component { - componentDidMount() { - console.info('componentDidMount 任务管理'); - } - - render() { - console.info('render 任务管理'); - - return ( - - ); - } -} diff --git a/examples/demo/src/services/devices.js b/examples/demo/src/services/devices.js deleted file mode 100644 index a2b3bad..0000000 --- a/examples/demo/src/services/devices.js +++ /dev/null @@ -1,19 +0,0 @@ -import http from '@/common/http'; -import { forEach, page } from 'celia'; -import moment from 'moment'; - -const list = []; -forEach(40, (num) => { - list.push({ - id: `产品${num}`, - ProductKey: Math.random().toString(36).substr(4), - NodeType: '设备', - UpdateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), - Status: num % 3 === 0 - }); -}); - -export function getDevices(current, pageSize) { - return http() - .then(() => page(list, current, pageSize)); -} diff --git a/examples/demo/vite.config.js b/examples/demo/vite.config.js deleted file mode 100644 index 2b6f198..0000000 --- a/examples/demo/vite.config.js +++ /dev/null @@ -1,55 +0,0 @@ -import { join } from 'path'; -import { defineConfig } from 'vite'; -import { getBabelInputPlugin } from '@rollup/plugin-babel'; -import reactRefresh from '../../packages/vite-plugin-react-refresh'; -import createExternal from '../../packages/vite-plugin-external'; - -// https://vitejs.dev/config/ -export default function ({ mode }) { - const isProd = mode === 'production'; - - return defineConfig({ - esbuild: isProd ? false : undefined, - resolve: { - alias: [ - { find: '@', replacement: join(__dirname, 'src') } - ] - }, - plugins: [ - createExternal({ - externals: { - '@linkdesign/components': 'LinkDesignComponents', - '@alicloud/console-components': 'AlicloudConsoleComponents', - react: '$linkdesign.React', - 'react-dom': '$linkdesign.ReactDOM', - 'react-router': '$linkdesign.ReactRouter', - 'prop-types': '$linkdesign.PropTypes', - history: '$linkdesign.History', - moment: '$linkdesign.Moment' - } - }), - reactRefresh({ - transformPlugins: [ - 'babel-plugin-jsx-advanced' - ] - }), - isProd && getBabelInputPlugin({ - babelHelpers: 'runtime' - }) - ], - server: { - open: true - }, - build: { - cssCodeSplit: false, - rollupOptions: { - output: { - manualChunks: undefined, - assetFileNames: 'assets/[name][extname]', - entryFileNames: 'assets/[name].js', - format: 'iife' - } - } - } - }); -} diff --git a/examples/react/.eslintrc.cjs b/examples/react/.eslintrc.cjs deleted file mode 100644 index 124520f..0000000 --- a/examples/react/.eslintrc.cjs +++ /dev/null @@ -1,21 +0,0 @@ -module.exports = { - root: true, - env: { browser: true, es2020: true }, - extends: [ - 'eslint:recommended', - 'plugin:react/recommended', - 'plugin:react/jsx-runtime', - 'plugin:react-hooks/recommended', - ], - ignorePatterns: ['dist', '.eslintrc.cjs'], - parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, - settings: { react: { version: '16.14' } }, - plugins: ['react-refresh'], - rules: { - 'react-refresh/only-export-components': [ - 'warn', - { allowConstantExport: true }, - ], - }, - } - \ No newline at end of file diff --git a/examples/react/.gitignore b/examples/react/.gitignore deleted file mode 100644 index a547bf3..0000000 --- a/examples/react/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? diff --git a/examples/react/README.md b/examples/react/README.md deleted file mode 100644 index f768e33..0000000 --- a/examples/react/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# React + Vite - -This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. - -Currently, two official plugins are available: - -- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh -- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh diff --git a/examples/react/mock/test.mjs b/examples/react/mock/test.mjs deleted file mode 100644 index 23cbc6a..0000000 --- a/examples/react/mock/test.mjs +++ /dev/null @@ -1,25 +0,0 @@ -export default { - '/hello': 'hello', - - '/hello2'(req, res) { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/html'); - res.end('hello2'); - }, - - '/hello3': { - handler(req, res) { - res.statusCode = 200; - res.setHeader('Content-Type', 'text/html'); - res.end('hello3'); - } - }, - - '/json': { - handler: { hello: 1 } - }, - - '/package': { - file: './package.json' - } -}; \ No newline at end of file diff --git a/examples/react/package.json b/examples/react/package.json deleted file mode 100644 index 39e4161..0000000 --- a/examples/react/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "react", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite --port=6543", - "build": "vite build", - "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", - "preview": "vite preview" - }, - "dependencies": { - "react": "^16.14.0", - "react-dom": "^16.14.0" - }, - "devDependencies": { - "@types/react": "^16.9.49", - "@types/react-dom": "^16.9.8", - "@vitejs/plugin-react": "^4.0.3", - "eslint": "^8.45.0", - "eslint-plugin-react": "^7.32.2", - "eslint-plugin-react-hooks": "^4.6.0", - "eslint-plugin-react-refresh": "^0.4.3", - "vite": "^4.4.5" - }, - "repository": "https://github.com/fengxinming/vite-plugins.git" -} diff --git a/examples/react/src/App.css b/examples/react/src/App.css deleted file mode 100644 index f639f64..0000000 --- a/examples/react/src/App.css +++ /dev/null @@ -1,43 +0,0 @@ -#root { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; -} - -.logo { - height: 6em; - padding: 1.5em; - will-change: filter; - transition: filter 300ms; -} -.logo:hover { - filter: drop-shadow(0 0 2em #646cffaa); -} -.logo.react:hover { - filter: drop-shadow(0 0 2em #61dafbaa); -} - -@keyframes logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} - -@media (prefers-reduced-motion: no-preference) { - a:nth-of-type(2) .logo { - animation: logo-spin infinite 20s linear; - } -} - -.card { - padding: 2em; -} - -.read-the-docs { - color: #888; -} - \ No newline at end of file diff --git a/examples/react/src/App.jsx b/examples/react/src/App.jsx deleted file mode 100644 index 51b2c79..0000000 --- a/examples/react/src/App.jsx +++ /dev/null @@ -1,25 +0,0 @@ -import { useState } from 'react' -import './App.css' - -function App() { - const [count, setCount] = useState(0) - - return ( - <> -

Vite + React

-
- -

- Edit src/App.jsx and save to test HMR -

-
-

- Click on the Vite and React logos to learn more -

- - ) -} - -export default App diff --git a/examples/react/src/index.css b/examples/react/src/index.css deleted file mode 100644 index 8aa9896..0000000 --- a/examples/react/src/index.css +++ /dev/null @@ -1,70 +0,0 @@ -:root { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; - - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; - - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - -webkit-text-size-adjust: 100%; -} - -a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; -} -a:hover { - color: #535bf2; -} - -body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; -} - -h1 { - font-size: 3.2em; - line-height: 1.1; -} - -button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; -} -button:hover { - border-color: #646cff; -} -button:focus, -button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; -} - -@media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } -} - \ No newline at end of file diff --git a/examples/react/src/main.jsx b/examples/react/src/main.jsx deleted file mode 100644 index d413dc4..0000000 --- a/examples/react/src/main.jsx +++ /dev/null @@ -1,9 +0,0 @@ -// import React from 'react' -import ReactDOM from 'react-dom' -import App from './App' -import './index.css' - -ReactDOM.render( - , - document.getElementById('root') -); \ No newline at end of file diff --git a/examples/react/vite.config.js b/examples/react/vite.config.js deleted file mode 100644 index 16d9b93..0000000 --- a/examples/react/vite.config.js +++ /dev/null @@ -1,47 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import vitePluginExternal from '../../packages/vite-plugin-external/src'; -import vitePluginCp from '../../packages/vite-plugin-cp/src'; -import vitePluginIncludeCSS from '../../packages/vite-plugin-include-css/src'; -import vitePluginMockData from '../../packages/vite-plugin-mock-data/src'; - -// https://vitejs.dev/config/ -export default defineConfig({ - plugins: [ - react(), - vitePluginExternal({ - externals: { - react: '$linkdesign.React', - 'react-dom': '$linkdesign.ReactDOM', - 'prop-types': '$linkdesign.PropTypes' - } - }), - vitePluginCp({ - targets: [ - { src: './node_modules/vite/dist', dest: 'dist/test' }, - { src: './node_modules/vite/dist', dest: 'dist/test2', flatten: false }, - { src: './node_modules/vite/README.md', dest: 'dist' }, - { src: './node_modules/vite/**/*.ts', dest: 'dist/types' } - ] - }), - vitePluginIncludeCSS(), - vitePluginMockData({ - mockAssetsDir: './node_modules/vite', - mockRoutesDir: './mock' - }) - ], - server: { - open: true - }, - build: { - cssCodeSplit: false, - rollupOptions: { - output: { - manualChunks: undefined, - assetFileNames: 'assets/[name][extname]', - entryFileNames: '[name].js', - format: 'iife' - } - } - } -}) diff --git a/examples/vite3-cp/index.js b/examples/vite3-cp/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite3-cp/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite3-cp/package.json b/examples/vite3-cp/package.json new file mode 100644 index 0000000..b94dbcc --- /dev/null +++ b/examples/vite3-cp/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite3-cp", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-cp": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-cp/vite.config.js b/examples/vite3-cp/vite.config.js new file mode 100644 index 0000000..b64eaf2 --- /dev/null +++ b/examples/vite3-cp/vite.config.js @@ -0,0 +1,22 @@ +import { defineConfig } from 'vite'; +import vitePluginCp from 'vite-plugin-cp'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginCp({ + targets: [ + { src: '../../node_modules/vite/dist', dest: 'dist/test' }, + { src: '../../node_modules/vite/dist', dest: 'dist/test2', flatten: false }, + { src: '../../node_modules/vite/README.md', dest: 'dist' }, + { src: '../../node_modules/vite/**/*.ts', dest: 'dist/types' } + ] + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/react/index.html b/examples/vite3-external/index.html similarity index 85% rename from examples/react/index.html rename to examples/vite3-external/index.html index 180209e..bb45931 100644 --- a/examples/react/index.html +++ b/examples/vite3-external/index.html @@ -8,6 +8,6 @@
- + diff --git a/examples/vite3-external/index.jsx b/examples/vite3-external/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite3-external/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite3-external/package.json b/examples/vite3-external/package.json new file mode 100644 index 0000000..ce421e5 --- /dev/null +++ b/examples/vite3-external/package.json @@ -0,0 +1,16 @@ +{ + "name": "vite3-external", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-external": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-external/vite.config.js b/examples/vite3-external/vite.config.js new file mode 100644 index 0000000..4af0961 --- /dev/null +++ b/examples/vite3-external/vite.config.js @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }) + ], + server: { + open: true + }, + build: { + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite3-hook-use/bar.js b/examples/vite3-hook-use/bar.js new file mode 100644 index 0000000..4356595 --- /dev/null +++ b/examples/vite3-hook-use/bar.js @@ -0,0 +1,3 @@ +export function bar() { + return 'bar'; +} diff --git a/examples/vite3-hook-use/index.js b/examples/vite3-hook-use/index.js new file mode 100644 index 0000000..8ed57c0 --- /dev/null +++ b/examples/vite3-hook-use/index.js @@ -0,0 +1,5 @@ +export function foo() { + return 'foo'; +} + +export * from './bar'; diff --git a/examples/vite3-hook-use/package.json b/examples/vite3-hook-use/package.json new file mode 100644 index 0000000..2b22b23 --- /dev/null +++ b/examples/vite3-hook-use/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite3-hook-use", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-hook-use": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-hook-use/vite.config.js b/examples/vite3-hook-use/vite.config.js new file mode 100644 index 0000000..c51b1fa --- /dev/null +++ b/examples/vite3-hook-use/vite.config.js @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite'; +import vitePluginHookUse from 'vite-plugin-hook-use'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginHookUse() + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite3-include-css/index.css b/examples/vite3-include-css/index.css new file mode 100644 index 0000000..cf6678a --- /dev/null +++ b/examples/vite3-include-css/index.css @@ -0,0 +1,12 @@ +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + color: #fff; + cursor: pointer; + transition: border-color .25s; +} \ No newline at end of file diff --git a/examples/vite3-include-css/index.html b/examples/vite3-include-css/index.html new file mode 100644 index 0000000..352eb6c --- /dev/null +++ b/examples/vite3-include-css/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite3-include-css/index.jsx b/examples/vite3-include-css/index.jsx new file mode 100644 index 0000000..7c9f08a --- /dev/null +++ b/examples/vite3-include-css/index.jsx @@ -0,0 +1,19 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +import './index.css'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite3-include-css/package.json b/examples/vite3-include-css/package.json new file mode 100644 index 0000000..d689fd2 --- /dev/null +++ b/examples/vite3-include-css/package.json @@ -0,0 +1,17 @@ +{ + "name": "vite3-include-css", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-external": "^4.0.2", + "vite-plugin-include-css": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-include-css/vite.config.js b/examples/vite3-include-css/vite.config.js new file mode 100644 index 0000000..73a8cbc --- /dev/null +++ b/examples/vite3-include-css/vite.config.js @@ -0,0 +1,29 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginIncludeCss from 'vite-plugin-include-css'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginIncludeCss() + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + minify: false, + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite3-mock-data/index.js b/examples/vite3-mock-data/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite3-mock-data/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite3-mock-data/mock/test.mjs b/examples/vite3-mock-data/mock/test.mjs new file mode 100644 index 0000000..1a0d795 --- /dev/null +++ b/examples/vite3-mock-data/mock/test.mjs @@ -0,0 +1,25 @@ +export default { + '/world': 'world', + + '/world2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world2'); + }, + + '/world3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world3'); + } + }, + + '/json2': { + handler: { world: 1 } + }, + + '/package2': { + file: './package.json' + } +}; diff --git a/examples/vite3-mock-data/mockAssets/blank.css b/examples/vite3-mock-data/mockAssets/blank.css new file mode 100644 index 0000000..e69de29 diff --git a/examples/vite3-mock-data/package.json b/examples/vite3-mock-data/package.json new file mode 100644 index 0000000..c1c1d25 --- /dev/null +++ b/examples/vite3-mock-data/package.json @@ -0,0 +1,15 @@ +{ + "name": "vite3-mock-data", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-mock-data": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-mock-data/vite.config.js b/examples/vite3-mock-data/vite.config.js new file mode 100644 index 0000000..6fb1105 --- /dev/null +++ b/examples/vite3-mock-data/vite.config.js @@ -0,0 +1,39 @@ +import { defineConfig } from 'vite'; +import vitePluginMockData from 'vite-plugin-mock-data'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginMockData({ + mockAssetsDir: './mockAssets', + mockRoutesDir: './mock', + mockRoutes: { + '/hello': 'hello', + '/hello2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello2'); + }, + '/hello3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello3'); + } + }, + '/json': { + handler: { hello: 1 } + }, + '/package.json': { + file: './package.json' + } + } + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite3-reverse-proxy/index.html b/examples/vite3-reverse-proxy/index.html new file mode 100644 index 0000000..06585d8 --- /dev/null +++ b/examples/vite3-reverse-proxy/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite3-reverse-proxy/index.jsx b/examples/vite3-reverse-proxy/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite3-reverse-proxy/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite3-reverse-proxy/package.json b/examples/vite3-reverse-proxy/package.json new file mode 100644 index 0000000..05f9981 --- /dev/null +++ b/examples/vite3-reverse-proxy/package.json @@ -0,0 +1,16 @@ +{ + "name": "vite3-reverse-proxy", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^3.2.7", + "vite-plugin-external": "^4.0.2", + "vite-plugin-reverse-proxy": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite3-reverse-proxy/vite.config.js b/examples/vite3-reverse-proxy/vite.config.js new file mode 100644 index 0000000..20bdb03 --- /dev/null +++ b/examples/vite3-reverse-proxy/vite.config.js @@ -0,0 +1,35 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginReverseProxy from 'vite-plugin-reverse-proxy'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginReverseProxy({ + targets: { + '/app.js': 'index.jsx' + } + }) + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + rollupOptions: { + output: { + manualChunks: undefined, + assetFileNames: 'assets/[name][extname]', + entryFileNames: '[name].js', + format: 'iife' + } + } + } +}); diff --git a/examples/vite4-cp/index.js b/examples/vite4-cp/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite4-cp/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite4-cp/package.json b/examples/vite4-cp/package.json new file mode 100644 index 0000000..99837f1 --- /dev/null +++ b/examples/vite4-cp/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite4-cp", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-cp": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-cp/vite.config.js b/examples/vite4-cp/vite.config.js new file mode 100644 index 0000000..b64eaf2 --- /dev/null +++ b/examples/vite4-cp/vite.config.js @@ -0,0 +1,22 @@ +import { defineConfig } from 'vite'; +import vitePluginCp from 'vite-plugin-cp'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginCp({ + targets: [ + { src: '../../node_modules/vite/dist', dest: 'dist/test' }, + { src: '../../node_modules/vite/dist', dest: 'dist/test2', flatten: false }, + { src: '../../node_modules/vite/README.md', dest: 'dist' }, + { src: '../../node_modules/vite/**/*.ts', dest: 'dist/types' } + ] + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite4-external/index.html b/examples/vite4-external/index.html new file mode 100644 index 0000000..bb45931 --- /dev/null +++ b/examples/vite4-external/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite4-external/index.jsx b/examples/vite4-external/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite4-external/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite4-external/package.json b/examples/vite4-external/package.json new file mode 100644 index 0000000..8441859 --- /dev/null +++ b/examples/vite4-external/package.json @@ -0,0 +1,16 @@ +{ + "name": "vite4-external", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-external": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-external/vite.config.js b/examples/vite4-external/vite.config.js new file mode 100644 index 0000000..4af0961 --- /dev/null +++ b/examples/vite4-external/vite.config.js @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }) + ], + server: { + open: true + }, + build: { + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite4-hook-use/bar.js b/examples/vite4-hook-use/bar.js new file mode 100644 index 0000000..4356595 --- /dev/null +++ b/examples/vite4-hook-use/bar.js @@ -0,0 +1,3 @@ +export function bar() { + return 'bar'; +} diff --git a/examples/vite4-hook-use/index.js b/examples/vite4-hook-use/index.js new file mode 100644 index 0000000..8ed57c0 --- /dev/null +++ b/examples/vite4-hook-use/index.js @@ -0,0 +1,5 @@ +export function foo() { + return 'foo'; +} + +export * from './bar'; diff --git a/examples/vite4-hook-use/package.json b/examples/vite4-hook-use/package.json new file mode 100644 index 0000000..6c47d9b --- /dev/null +++ b/examples/vite4-hook-use/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite4-hook-use", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-hook-use": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-hook-use/vite.config.js b/examples/vite4-hook-use/vite.config.js new file mode 100644 index 0000000..c51b1fa --- /dev/null +++ b/examples/vite4-hook-use/vite.config.js @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite'; +import vitePluginHookUse from 'vite-plugin-hook-use'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginHookUse() + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite4-include-css/index.css b/examples/vite4-include-css/index.css new file mode 100644 index 0000000..cf6678a --- /dev/null +++ b/examples/vite4-include-css/index.css @@ -0,0 +1,12 @@ +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + color: #fff; + cursor: pointer; + transition: border-color .25s; +} \ No newline at end of file diff --git a/examples/vite4-include-css/index.html b/examples/vite4-include-css/index.html new file mode 100644 index 0000000..352eb6c --- /dev/null +++ b/examples/vite4-include-css/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite4-include-css/index.jsx b/examples/vite4-include-css/index.jsx new file mode 100644 index 0000000..7c9f08a --- /dev/null +++ b/examples/vite4-include-css/index.jsx @@ -0,0 +1,19 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +import './index.css'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite4-include-css/package.json b/examples/vite4-include-css/package.json new file mode 100644 index 0000000..0f57b7d --- /dev/null +++ b/examples/vite4-include-css/package.json @@ -0,0 +1,17 @@ +{ + "name": "vite4-include-css", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-external": "^4.0.2", + "vite-plugin-include-css": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-include-css/vite.config.js b/examples/vite4-include-css/vite.config.js new file mode 100644 index 0000000..73a8cbc --- /dev/null +++ b/examples/vite4-include-css/vite.config.js @@ -0,0 +1,29 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginIncludeCss from 'vite-plugin-include-css'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginIncludeCss() + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + minify: false, + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite4-mock-data/index.js b/examples/vite4-mock-data/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite4-mock-data/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite4-mock-data/mock/test.mjs b/examples/vite4-mock-data/mock/test.mjs new file mode 100644 index 0000000..1a0d795 --- /dev/null +++ b/examples/vite4-mock-data/mock/test.mjs @@ -0,0 +1,25 @@ +export default { + '/world': 'world', + + '/world2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world2'); + }, + + '/world3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world3'); + } + }, + + '/json2': { + handler: { world: 1 } + }, + + '/package2': { + file: './package.json' + } +}; diff --git a/examples/vite4-mock-data/mockAssets/blank.css b/examples/vite4-mock-data/mockAssets/blank.css new file mode 100644 index 0000000..e69de29 diff --git a/examples/vite4-mock-data/package.json b/examples/vite4-mock-data/package.json new file mode 100644 index 0000000..3d6f9ba --- /dev/null +++ b/examples/vite4-mock-data/package.json @@ -0,0 +1,15 @@ +{ + "name": "vite4-mock-data", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-mock-data": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-mock-data/vite.config.js b/examples/vite4-mock-data/vite.config.js new file mode 100644 index 0000000..6fb1105 --- /dev/null +++ b/examples/vite4-mock-data/vite.config.js @@ -0,0 +1,39 @@ +import { defineConfig } from 'vite'; +import vitePluginMockData from 'vite-plugin-mock-data'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginMockData({ + mockAssetsDir: './mockAssets', + mockRoutesDir: './mock', + mockRoutes: { + '/hello': 'hello', + '/hello2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello2'); + }, + '/hello3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello3'); + } + }, + '/json': { + handler: { hello: 1 } + }, + '/package.json': { + file: './package.json' + } + } + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite4-reverse-proxy/index.html b/examples/vite4-reverse-proxy/index.html new file mode 100644 index 0000000..06585d8 --- /dev/null +++ b/examples/vite4-reverse-proxy/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite4-reverse-proxy/index.jsx b/examples/vite4-reverse-proxy/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite4-reverse-proxy/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite4-reverse-proxy/package.json b/examples/vite4-reverse-proxy/package.json new file mode 100644 index 0000000..24c381b --- /dev/null +++ b/examples/vite4-reverse-proxy/package.json @@ -0,0 +1,16 @@ +{ + "name": "vite4-reverse-proxy", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^4.5.0", + "vite-plugin-external": "^4.0.2", + "vite-plugin-reverse-proxy": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite4-reverse-proxy/vite.config.js b/examples/vite4-reverse-proxy/vite.config.js new file mode 100644 index 0000000..20bdb03 --- /dev/null +++ b/examples/vite4-reverse-proxy/vite.config.js @@ -0,0 +1,35 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginReverseProxy from 'vite-plugin-reverse-proxy'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginReverseProxy({ + targets: { + '/app.js': 'index.jsx' + } + }) + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + rollupOptions: { + output: { + manualChunks: undefined, + assetFileNames: 'assets/[name][extname]', + entryFileNames: '[name].js', + format: 'iife' + } + } + } +}); diff --git a/examples/vite5-cp/index.js b/examples/vite5-cp/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite5-cp/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite5-cp/package.json b/examples/vite5-cp/package.json new file mode 100644 index 0000000..976b857 --- /dev/null +++ b/examples/vite5-cp/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite5-cp", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-cp": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-cp/vite.config.js b/examples/vite5-cp/vite.config.js new file mode 100644 index 0000000..b64eaf2 --- /dev/null +++ b/examples/vite5-cp/vite.config.js @@ -0,0 +1,22 @@ +import { defineConfig } from 'vite'; +import vitePluginCp from 'vite-plugin-cp'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginCp({ + targets: [ + { src: '../../node_modules/vite/dist', dest: 'dist/test' }, + { src: '../../node_modules/vite/dist', dest: 'dist/test2', flatten: false }, + { src: '../../node_modules/vite/README.md', dest: 'dist' }, + { src: '../../node_modules/vite/**/*.ts', dest: 'dist/types' } + ] + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite5-external/index.html b/examples/vite5-external/index.html new file mode 100644 index 0000000..bb45931 --- /dev/null +++ b/examples/vite5-external/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite5-external/index.jsx b/examples/vite5-external/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite5-external/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite5-external/package.json b/examples/vite5-external/package.json new file mode 100644 index 0000000..54c89ce --- /dev/null +++ b/examples/vite5-external/package.json @@ -0,0 +1,15 @@ +{ + "name": "vite5-external", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-external": "^4.0.2" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-external/vite.config.js b/examples/vite5-external/vite.config.js new file mode 100644 index 0000000..4af0961 --- /dev/null +++ b/examples/vite5-external/vite.config.js @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }) + ], + server: { + open: true + }, + build: { + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite5-hook-use/bar.js b/examples/vite5-hook-use/bar.js new file mode 100644 index 0000000..4356595 --- /dev/null +++ b/examples/vite5-hook-use/bar.js @@ -0,0 +1,3 @@ +export function bar() { + return 'bar'; +} diff --git a/examples/vite5-hook-use/index.js b/examples/vite5-hook-use/index.js new file mode 100644 index 0000000..8ed57c0 --- /dev/null +++ b/examples/vite5-hook-use/index.js @@ -0,0 +1,5 @@ +export function foo() { + return 'foo'; +} + +export * from './bar'; diff --git a/examples/vite5-hook-use/package.json b/examples/vite5-hook-use/package.json new file mode 100644 index 0000000..089a714 --- /dev/null +++ b/examples/vite5-hook-use/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite5-hook-use", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "vite build" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-hook-use": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-hook-use/vite.config.js b/examples/vite5-hook-use/vite.config.js new file mode 100644 index 0000000..c51b1fa --- /dev/null +++ b/examples/vite5-hook-use/vite.config.js @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite'; +import vitePluginHookUse from 'vite-plugin-hook-use'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginHookUse() + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite5-include-css/index.css b/examples/vite5-include-css/index.css new file mode 100644 index 0000000..cf6678a --- /dev/null +++ b/examples/vite5-include-css/index.css @@ -0,0 +1,12 @@ +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + color: #fff; + cursor: pointer; + transition: border-color .25s; +} \ No newline at end of file diff --git a/examples/vite5-include-css/index.html b/examples/vite5-include-css/index.html new file mode 100644 index 0000000..352eb6c --- /dev/null +++ b/examples/vite5-include-css/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite5-include-css/index.jsx b/examples/vite5-include-css/index.jsx new file mode 100644 index 0000000..7c9f08a --- /dev/null +++ b/examples/vite5-include-css/index.jsx @@ -0,0 +1,19 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +import './index.css'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite5-include-css/package.json b/examples/vite5-include-css/package.json new file mode 100644 index 0000000..d171438 --- /dev/null +++ b/examples/vite5-include-css/package.json @@ -0,0 +1,17 @@ +{ + "name": "vite5-include-css", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-external": "^4.0.2", + "vite-plugin-include-css": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-include-css/vite.config.js b/examples/vite5-include-css/vite.config.js new file mode 100644 index 0000000..73a8cbc --- /dev/null +++ b/examples/vite5-include-css/vite.config.js @@ -0,0 +1,29 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginIncludeCss from 'vite-plugin-include-css'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginIncludeCss() + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + minify: false, + rollupOptions: { + output: { + format: 'iife' + } + } + } +}); diff --git a/examples/vite5-mock-data/index.js b/examples/vite5-mock-data/index.js new file mode 100644 index 0000000..7efce94 --- /dev/null +++ b/examples/vite5-mock-data/index.js @@ -0,0 +1,3 @@ +export function foo() { + return 'foo'; +} diff --git a/examples/vite5-mock-data/mock/test.mjs b/examples/vite5-mock-data/mock/test.mjs new file mode 100644 index 0000000..1a0d795 --- /dev/null +++ b/examples/vite5-mock-data/mock/test.mjs @@ -0,0 +1,25 @@ +export default { + '/world': 'world', + + '/world2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world2'); + }, + + '/world3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('world3'); + } + }, + + '/json2': { + handler: { world: 1 } + }, + + '/package2': { + file: './package.json' + } +}; diff --git a/examples/vite5-mock-data/mockAssets/blank.css b/examples/vite5-mock-data/mockAssets/blank.css new file mode 100644 index 0000000..e69de29 diff --git a/examples/vite5-mock-data/package.json b/examples/vite5-mock-data/package.json new file mode 100644 index 0000000..e0abd72 --- /dev/null +++ b/examples/vite5-mock-data/package.json @@ -0,0 +1,15 @@ +{ + "name": "vite5-mock-data", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-mock-data": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-mock-data/vite.config.js b/examples/vite5-mock-data/vite.config.js new file mode 100644 index 0000000..6fb1105 --- /dev/null +++ b/examples/vite5-mock-data/vite.config.js @@ -0,0 +1,39 @@ +import { defineConfig } from 'vite'; +import vitePluginMockData from 'vite-plugin-mock-data'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginMockData({ + mockAssetsDir: './mockAssets', + mockRoutesDir: './mock', + mockRoutes: { + '/hello': 'hello', + '/hello2'(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello2'); + }, + '/hello3': { + handler(req, res) { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/html'); + res.end('hello3'); + } + }, + '/json': { + handler: { hello: 1 } + }, + '/package.json': { + file: './package.json' + } + } + }) + ], + build: { + lib: { + entry: 'index.js', + formats: ['es'] + } + } +}); diff --git a/examples/vite5-reverse-proxy/index.html b/examples/vite5-reverse-proxy/index.html new file mode 100644 index 0000000..06585d8 --- /dev/null +++ b/examples/vite5-reverse-proxy/index.html @@ -0,0 +1,13 @@ + + + + + + Vite + React + + +
+ + + + diff --git a/examples/vite5-reverse-proxy/index.jsx b/examples/vite5-reverse-proxy/index.jsx new file mode 100644 index 0000000..047b7d7 --- /dev/null +++ b/examples/vite5-reverse-proxy/index.jsx @@ -0,0 +1,17 @@ +import React, { useState } from 'react'; +import ReactDOM from 'react-dom'; + +function App() { + const [count, setCount] = useState(0); + return ( + <> +

Count: {count}

+ + + ); +} + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/examples/vite5-reverse-proxy/package.json b/examples/vite5-reverse-proxy/package.json new file mode 100644 index 0000000..8f685cd --- /dev/null +++ b/examples/vite5-reverse-proxy/package.json @@ -0,0 +1,16 @@ +{ + "name": "vite5-reverse-proxy", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "dependencies": { + "vite": "^5.0.2", + "vite-plugin-external": "^4.0.2", + "vite-plugin-reverse-proxy": "^4.0.0" + }, + "repository": "https://github.com/fengxinming/vite-plugins.git" +} \ No newline at end of file diff --git a/examples/vite5-reverse-proxy/vite.config.js b/examples/vite5-reverse-proxy/vite.config.js new file mode 100644 index 0000000..20bdb03 --- /dev/null +++ b/examples/vite5-reverse-proxy/vite.config.js @@ -0,0 +1,35 @@ +import { defineConfig } from 'vite'; +import vitePluginExternal from 'vite-plugin-external'; +import vitePluginReverseProxy from 'vite-plugin-reverse-proxy'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vitePluginExternal({ + externals: { + react: '$linkdesign.React', + 'react-dom': '$linkdesign.ReactDOM', + 'prop-types': '$linkdesign.PropTypes' + } + }), + vitePluginReverseProxy({ + targets: { + '/app.js': 'index.jsx' + } + }) + ], + server: { + open: true + }, + build: { + cssCodeSplit: false, + rollupOptions: { + output: { + manualChunks: undefined, + assetFileNames: 'assets/[name][extname]', + entryFileNames: '[name].js', + format: 'iife' + } + } + } +}); diff --git a/lerna.json b/lerna.json new file mode 100644 index 0000000..feeba14 --- /dev/null +++ b/lerna.json @@ -0,0 +1,16 @@ +{ + "npmClient": "tnpm", + "npmClientArgs": [ + "--package-lock=false" + ], + "version": "independent", + "packages": [ + "packages/*", + "examples/*" + ], + "command": { + "bootstrap": { + "hoist": true + } + } +} \ No newline at end of file diff --git a/package.json b/package.json index 989081c..f843272 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,13 @@ "example": "examples" }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "build:cp": "pnpm --filter vite-plugin-cp build" + "deps": "npm run clean && tnpm install && lerna bootstrap", + "clean": "tnpm install lerna@6 && lerna clean --yes && rm -rf ./node_modules", + "eslint": "eslint --ext .js,.jsx,.ts,.tsx,.mjs --fix --ignore-path .eslintignore ./", + "build": "lerna run build", + "prepare": "husky install", + "link": "lerna link", + "docs": "typedoc" }, "repository": { "type": "git", @@ -21,34 +26,25 @@ }, "homepage": "https://github.com/fengxinming/vite-plugins#readme", "dependencies": { - "@babel/core": "^7.14.0", - "@babel/eslint-parser": "^7.13.14", - "@babel/eslint-plugin": "^7.13.16", - "@babel/preset-env": "^7.14.7", + "@rollup/plugin-typescript": "^11.1.5", + "lerna": "^6.6.2", + "vite": "^4.5.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "devDependencies": { "@babel/preset-react": "^7.13.13", "@commitlint/cli": "^17.6.1", "@commitlint/config-conventional": "^17.6.1", - "@typescript-eslint/eslint-plugin": "^6.4.1", - "@typescript-eslint/parser": "^6.4.1", "eslint": "^8.48.0", - "eslint-config-fe": "^1.0.0", + "eslint-config-fe": "^2.1.0", "eslint-plugin-jsx-advanced": "^1.0.0", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-hooks": "^4.2.0", - "husky": "^4.3.8", - "lint-staged": "^13.2.1", - "react": "^16.14.0" - }, - "husky": { - "hooks": { - "pre-commit": "lint-staged", - "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS" - } - }, - "lint-staged": { - "*.{js,jsx}": [ - "eslint --fix", - "git add" - ] + "husky": "^8.0.3", + "lint-staged": "^12.5.0", + "react": "^16.14.0", + "typedoc": "^0.25.4" } -} \ No newline at end of file +} diff --git a/packages/vite-plugin-cp/README.md b/packages/vite-plugin-cp/README.md index ad364e8..a63074f 100644 --- a/packages/vite-plugin-cp/README.md +++ b/packages/vite-plugin-cp/README.md @@ -32,16 +32,16 @@ export interface Options { } ``` -* `hook` - Default `'writeBundle'`, vite hook the plugin should use. -* `enforce` - it may be needed to enforce the order of the plugin or only apply at build time. -* `globbyOptions` - [globby options](https://github.com/mrmlnc/fast-glob#options-3) +* `hook` - Default `'closeBundle'`, vite hook the plugin should use. +* `enforce` - It may be needed to enforce the order of the plugin or only apply at build time. +* `globbyOptions` - [globby options](https://github.com/sindresorhus/globby#options) * `cwd` - Default `process.cwd()`, The current working directory in which to search. * `targets` - Array of targets to copy. A target is an object with properties: * src - Path or glob of what to copy. * dest - One or more destinations where to copy. - * rename - Change destination file. + * rename - Rename the file after copying.. * flatten - Remove the directory structure of copied files. - * transform - Modify file contents. + * transform - Transform the file before copying. ## Usage @@ -73,4 +73,6 @@ export default defineConfig({ ## Examples -**[See demo](examples/react)** +* [See vite3 demo](../../examples/vite3-cp) +* [See vite4 demo](../../examples/vite4-cp) +* [See vite5 demo](../../examples/vite5-cp) diff --git a/packages/vite-plugin-cp/dist/index.cjs b/packages/vite-plugin-cp/dist/index.cjs deleted file mode 100644 index 18c1652..0000000 --- a/packages/vite-plugin-cp/dist/index.cjs +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -var node_path = require('node:path'); -var fs = require('fs'); -var promises = require('fs/promises'); -var fsExtra = require('fs-extra'); -var globby = require('globby'); - -function makeCopy(transform) { - return transform - ? function (from, to) { - return promises.readFile(from) - .then((buf) => transform(buf, from)) - .then((data) => { - const { dir } = node_path.parse(to); - return fsExtra.pathExists(dir).then((itDoes) => { - if (!itDoes) { - return fsExtra.mkdirs(dir); - } - }).then(() => { - return promises.writeFile(to, data); - }); - }); - } - : fsExtra.copy; -} -function transformName(name, rename) { - if (typeof rename === 'function') { - return rename(name) || name; - } - return rename || name; -} -function createPlugin(opts) { - const { hook = 'writeBundle', enforce, targets, cwd = process.cwd(), globbyOptions } = opts || {}; - const plugin = { - name: 'vite:cp' - }; - if (enforce) { - plugin.enforce = enforce; - } - if (!Array.isArray(targets) || !targets.length) { - return plugin; - } - const toAbsolutePath = (pth) => { - if (!node_path.isAbsolute(pth)) { - pth = node_path.join(cwd, pth); - } - return pth; - }; - let called = false; - plugin[hook] = async function () { - // copy once - if (called) { - return; - } - called = true; - const startTime = Date.now(); - await Promise.all(targets.map(({ src, dest, rename, flatten, transform }) => { - dest = toAbsolutePath(dest); - const cp = makeCopy(transform); - const glob = (pattern) => { - let notFlatten = false; - try { - notFlatten = fs.statSync(pattern).isDirectory() && flatten === false; - } - catch (e) { } - return globby.globby(pattern, globbyOptions).then((matchedPaths) => { - if (!matchedPaths.length) { - throw new Error(`Could not find files with "${pattern}"`); - } - return matchedPaths.map((matchedPath) => { - matchedPath = toAbsolutePath(matchedPath); - const outputToDest = notFlatten - ? function (matchedPath) { - const tmp = node_path.parse(node_path.relative(pattern, matchedPath)); - return cp(matchedPath, node_path.join(dest, tmp.dir, transformName(tmp.base, rename))); - } - : function (matchedPath) { - return cp(matchedPath, node_path.join(dest, transformName(node_path.parse(matchedPath).base, rename))); - }; - return outputToDest(matchedPath); - }); - }); - }; - if (typeof src === 'string') { - return glob(src); - } - else if (Array.isArray(src)) { - return Promise.all(src.map(glob)); - } - return null; - })); - console.info(`Done in ${Number((Date.now() - startTime) / 1000).toFixed(1)}s`); - }; - return plugin; -} - -module.exports = createPlugin; diff --git a/packages/vite-plugin-cp/dist/index.d.ts b/packages/vite-plugin-cp/dist/index.d.ts index 9f1dc78..95618e3 100644 --- a/packages/vite-plugin-cp/dist/index.d.ts +++ b/packages/vite-plugin-cp/dist/index.d.ts @@ -2,17 +2,35 @@ import { Plugin } from 'vite'; import { Options as GlobbyOptions } from 'globby'; export interface Target { + /** Path or glob of what to copy. */ src: string | string[]; + /** One or more destinations where to copy. */ dest: string; + /** Rename the file after copying. */ rename?: string | ((name: string) => string); + /** Remove the directory structure of copied files. */ flatten?: boolean; + /** Options for globby. See more at https://github.com/sindresorhus/globby#options */ + globbyOptions?: GlobbyOptions; + /** Transform the file before copying. */ transform?: (buf: Buffer, matchedPath: string) => string | Buffer | Promise; } export interface Options { + /** Default `'closeBundle'`, vite hook the plugin should use. */ hook?: string; + /** It may be needed to enforce the order of the plugin or only apply at build time. */ enforce?: 'pre' | 'post'; + /** Options for globby. See more at https://github.com/sindresorhus/globby#options */ globbyOptions?: GlobbyOptions; + /** Default `process.cwd()`, The current working directory in which to search. */ cwd?: string; + /** Array of targets to copy. A target is an object with properties */ targets: Target[]; } +/** + * Copy files and directories. + * + * @param opts Options + * @returns a vite plugin + */ export default function createPlugin(opts: Options): Plugin; diff --git a/packages/vite-plugin-cp/dist/index.js b/packages/vite-plugin-cp/dist/index.js new file mode 100644 index 0000000..d54c6f6 --- /dev/null +++ b/packages/vite-plugin-cp/dist/index.js @@ -0,0 +1,87 @@ +"use strict"; +const node_path = require("node:path"); +const node_fs = require("node:fs"); +const promises = require("node:fs/promises"); +const fsExtra = require("fs-extra"); +const globby = require("globby"); +function makeCopy(transform) { + return transform ? function(from, to) { + return promises.readFile(from).then((buf) => transform(buf, from)).then((data) => { + const { dir } = node_path.parse(to); + return fsExtra.pathExists(dir).then((itDoes) => { + if (!itDoes) { + return fsExtra.mkdirs(dir); + } + }).then(() => { + return promises.writeFile(to, data); + }); + }); + } : fsExtra.copy; +} +function transformName(name, rename) { + if (typeof rename === "function") { + return rename(name) || name; + } + return rename || name; +} +function createPlugin(opts) { + const { hook = "closeBundle", enforce, targets, cwd = process.cwd(), globbyOptions } = opts || {}; + const plugin = { + name: "vite:cp" + }; + if (enforce) { + plugin.enforce = enforce; + } + if (!Array.isArray(targets) || !targets.length) { + return plugin; + } + const toAbsolutePath = (pth) => { + if (!node_path.isAbsolute(pth)) { + pth = node_path.join(cwd, pth); + } + return pth; + }; + let called = false; + plugin[hook] = async function() { + if (called) { + return; + } + called = true; + const startTime = Date.now(); + await Promise.all(targets.map(({ src, dest, rename, flatten, globbyOptions: gOptions, transform }) => { + dest = toAbsolutePath(dest); + const cp = makeCopy(transform); + const glob = (pattern) => { + let notFlatten = false; + try { + notFlatten = node_fs.statSync(pattern).isDirectory() && flatten === false; + } catch (e) { + } + return globby.globby(pattern, Object.assign({}, globbyOptions, gOptions)).then((matchedPaths) => { + if (!matchedPaths.length) { + throw new Error(`Could not find files with "${pattern}"`); + } + return matchedPaths.map((matchedPath) => { + matchedPath = toAbsolutePath(matchedPath); + const outputToDest = notFlatten ? function(matchedPath2) { + const tmp = node_path.parse(node_path.relative(pattern, matchedPath2)); + return cp(matchedPath2, node_path.join(dest, tmp.dir, transformName(tmp.base, rename))); + } : function(matchedPath2) { + return cp(matchedPath2, node_path.join(dest, transformName(node_path.parse(matchedPath2).base, rename))); + }; + return outputToDest(matchedPath); + }); + }); + }; + if (typeof src === "string") { + return glob(src); + } else if (Array.isArray(src)) { + return Promise.all(src.map(glob)); + } + return null; + })); + console.info(`Done in ${Number((Date.now() - startTime) / 1e3).toFixed(1)}s`); + }; + return plugin; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-cp/dist/index.mjs b/packages/vite-plugin-cp/dist/index.mjs index 5d2928e..16a3fd4 100644 --- a/packages/vite-plugin-cp/dist/index.mjs +++ b/packages/vite-plugin-cp/dist/index.mjs @@ -1,96 +1,88 @@ -import { isAbsolute, join, parse, relative } from 'node:path'; -import { statSync } from 'fs'; -import { readFile, writeFile } from 'fs/promises'; -import { pathExists, mkdirs, copy } from 'fs-extra'; -import { globby } from 'globby'; - +import { isAbsolute, join, parse, relative } from "node:path"; +import { statSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { pathExists, mkdirs, copy } from "fs-extra"; +import { globby } from "globby"; function makeCopy(transform) { - return transform - ? function (from, to) { - return readFile(from) - .then((buf) => transform(buf, from)) - .then((data) => { - const { dir } = parse(to); - return pathExists(dir).then((itDoes) => { - if (!itDoes) { - return mkdirs(dir); - } - }).then(() => { - return writeFile(to, data); - }); - }); + return transform ? function(from, to) { + return readFile(from).then((buf) => transform(buf, from)).then((data) => { + const { dir } = parse(to); + return pathExists(dir).then((itDoes) => { + if (!itDoes) { + return mkdirs(dir); } - : copy; + }).then(() => { + return writeFile(to, data); + }); + }); + } : copy; } function transformName(name, rename) { - if (typeof rename === 'function') { - return rename(name) || name; - } - return rename || name; + if (typeof rename === "function") { + return rename(name) || name; + } + return rename || name; } function createPlugin(opts) { - const { hook = 'writeBundle', enforce, targets, cwd = process.cwd(), globbyOptions } = opts || {}; - const plugin = { - name: 'vite:cp' - }; - if (enforce) { - plugin.enforce = enforce; + const { hook = "closeBundle", enforce, targets, cwd = process.cwd(), globbyOptions } = opts || {}; + const plugin = { + name: "vite:cp" + }; + if (enforce) { + plugin.enforce = enforce; + } + if (!Array.isArray(targets) || !targets.length) { + return plugin; + } + const toAbsolutePath = (pth) => { + if (!isAbsolute(pth)) { + pth = join(cwd, pth); } - if (!Array.isArray(targets) || !targets.length) { - return plugin; + return pth; + }; + let called = false; + plugin[hook] = async function() { + if (called) { + return; } - const toAbsolutePath = (pth) => { - if (!isAbsolute(pth)) { - pth = join(cwd, pth); + called = true; + const startTime = Date.now(); + await Promise.all(targets.map(({ src, dest, rename, flatten, globbyOptions: gOptions, transform }) => { + dest = toAbsolutePath(dest); + const cp = makeCopy(transform); + const glob = (pattern) => { + let notFlatten = false; + try { + notFlatten = statSync(pattern).isDirectory() && flatten === false; + } catch (e) { } - return pth; - }; - let called = false; - plugin[hook] = async function () { - // copy once - if (called) { - return; - } - called = true; - const startTime = Date.now(); - await Promise.all(targets.map(({ src, dest, rename, flatten, transform }) => { - dest = toAbsolutePath(dest); - const cp = makeCopy(transform); - const glob = (pattern) => { - let notFlatten = false; - try { - notFlatten = statSync(pattern).isDirectory() && flatten === false; - } - catch (e) { } - return globby(pattern, globbyOptions).then((matchedPaths) => { - if (!matchedPaths.length) { - throw new Error(`Could not find files with "${pattern}"`); - } - return matchedPaths.map((matchedPath) => { - matchedPath = toAbsolutePath(matchedPath); - const outputToDest = notFlatten - ? function (matchedPath) { - const tmp = parse(relative(pattern, matchedPath)); - return cp(matchedPath, join(dest, tmp.dir, transformName(tmp.base, rename))); - } - : function (matchedPath) { - return cp(matchedPath, join(dest, transformName(parse(matchedPath).base, rename))); - }; - return outputToDest(matchedPath); - }); - }); + return globby(pattern, Object.assign({}, globbyOptions, gOptions)).then((matchedPaths) => { + if (!matchedPaths.length) { + throw new Error(`Could not find files with "${pattern}"`); + } + return matchedPaths.map((matchedPath) => { + matchedPath = toAbsolutePath(matchedPath); + const outputToDest = notFlatten ? function(matchedPath2) { + const tmp = parse(relative(pattern, matchedPath2)); + return cp(matchedPath2, join(dest, tmp.dir, transformName(tmp.base, rename))); + } : function(matchedPath2) { + return cp(matchedPath2, join(dest, transformName(parse(matchedPath2).base, rename))); }; - if (typeof src === 'string') { - return glob(src); - } - else if (Array.isArray(src)) { - return Promise.all(src.map(glob)); - } - return null; - })); - console.info(`Done in ${Number((Date.now() - startTime) / 1000).toFixed(1)}s`); - }; - return plugin; + return outputToDest(matchedPath); + }); + }); + }; + if (typeof src === "string") { + return glob(src); + } else if (Array.isArray(src)) { + return Promise.all(src.map(glob)); + } + return null; + })); + console.info(`Done in ${Number((Date.now() - startTime) / 1e3).toFixed(1)}s`); + }; + return plugin; } - -export { createPlugin as default }; +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-cp/package.json b/packages/vite-plugin-cp/package.json index dcb65cc..cfa5bdf 100644 --- a/packages/vite-plugin-cp/package.json +++ b/packages/vite-plugin-cp/package.json @@ -2,19 +2,24 @@ "name": "vite-plugin-cp", "version": "4.0.2", "description": "Copy files after building bundles.", - "main": "./dist/index.cjs", - "module": "./dist/index.mjs", "types": "./dist/index.d.ts", + "module": "./dist/index.mjs", + "main": "./dist/index.js", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.cjs" + "require": "./dist/index.js" } }, + "engines": { + "node": ">=14.18.0", + "vite": ">=3.1.0" + }, "scripts": { - "release": "npm publish", - "build": "rollup --config ./rollup.config.mjs" + "build": "vite build", + "watch": "vite build --watch", + "release": "npm publish" }, "repository": { "type": "git", @@ -31,18 +36,11 @@ }, "homepage": "https://github.com/fengxinming/vite-plugins#readme", "dependencies": { + "@types/node": "^14.18.63", "fs-extra": "^11.1.1", "globby": "^13.2.2" }, - "devDependencies": { - "@rollup/plugin-typescript": "^11.1.3", - "@types/node": "^20.5.9", - "rollup": "^3.28.1", - "rollup-plugin-empty": "^1.0.0", - "rollup-plugin-filesize": "^10.0.0", - "vite": "^4.4.9" - }, "files": [ "dist" ] -} +} \ No newline at end of file diff --git a/packages/vite-plugin-cp/rollup.config.mjs b/packages/vite-plugin-cp/rollup.config.mjs deleted file mode 100644 index 6810656..0000000 --- a/packages/vite-plugin-cp/rollup.config.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'rollup'; -import typescript from '@rollup/plugin-typescript'; -import empty from 'rollup-plugin-empty'; -import filesize from 'rollup-plugin-filesize'; - -export default [ - defineConfig({ - input: 'src/index.ts', - plugins: [ - empty({ - dir: 'dist' - }), - typescript({ - tsconfig: './tsconfig.build.json' - }), - filesize() - ], - output: [{ - file: 'dist/index.mjs', - format: 'esm', - exports: 'auto' - }, { - file: 'dist/index.cjs', - format: 'cjs', - exports: 'auto', - externalLiveBindings: false - }] - }) -]; diff --git a/packages/vite-plugin-cp/src/index.ts b/packages/vite-plugin-cp/src/index.ts index fb0302f..0150879 100644 --- a/packages/vite-plugin-cp/src/index.ts +++ b/packages/vite-plugin-cp/src/index.ts @@ -1,23 +1,44 @@ import { join, isAbsolute, parse, relative } from 'node:path'; -import { statSync } from 'fs'; -import { readFile, writeFile } from 'fs/promises'; +import { statSync } from 'node:fs'; +import { readFile, writeFile } from 'node:fs/promises'; import { Plugin } from 'vite'; import { copy, pathExists, mkdirs } from 'fs-extra'; import { globby, Options as GlobbyOptions } from 'globby'; export interface Target { + /** Path or glob of what to copy. */ src: string | string[]; + + /** One or more destinations where to copy. */ dest: string; + + /** Rename the file after copying. */ rename?: string | ((name: string) => string); + + /** Remove the directory structure of copied files. */ flatten?: boolean; + + /** Options for globby. See more at https://github.com/sindresorhus/globby#options */ + globbyOptions?: GlobbyOptions; + + /** Transform the file before copying. */ transform?: (buf: Buffer, matchedPath: string) => string | Buffer | Promise; } export interface Options { + /** Default `'closeBundle'`, vite hook the plugin should use. */ hook?: string; + + /** It may be needed to enforce the order of the plugin or only apply at build time. */ enforce?: 'pre' | 'post'; + + /** Options for globby. See more at https://github.com/sindresorhus/globby#options */ globbyOptions?: GlobbyOptions; + + /** Default `process.cwd()`, The current working directory in which to search. */ cwd?: string; + + /** Array of targets to copy. A target is an object with properties */ targets: Target[]; } @@ -48,9 +69,15 @@ function transformName(name: string, rename?: string | ((name: string) => string return rename || name; } +/** + * Copy files and directories. + * + * @param opts Options + * @returns a vite plugin + */ export default function createPlugin(opts: Options): Plugin { const { - hook = 'writeBundle', + hook = 'closeBundle', enforce, targets, cwd = process.cwd(), @@ -87,7 +114,7 @@ export default function createPlugin(opts: Options): Plugin { called = true; const startTime = Date.now(); - await Promise.all(targets.map(({ src, dest, rename, flatten, transform }) => { + await Promise.all(targets.map(({ src, dest, rename, flatten, globbyOptions: gOptions, transform }) => { dest = toAbsolutePath(dest); const cp = makeCopy(transform); @@ -98,7 +125,7 @@ export default function createPlugin(opts: Options): Plugin { } catch (e) {} - return globby(pattern, globbyOptions).then((matchedPaths) => { + return globby(pattern, Object.assign({}, globbyOptions, gOptions)).then((matchedPaths) => { if (!matchedPaths.length) { throw new Error(`Could not find files with "${pattern}"`); } diff --git a/packages/vite-plugin-cp/tsconfig.build.json b/packages/vite-plugin-cp/tsconfig.build.json deleted file mode 100644 index 357ac49..0000000 --- a/packages/vite-plugin-cp/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "dist" - } - } \ No newline at end of file diff --git a/packages/vite-plugin-cp/tsconfig.json b/packages/vite-plugin-cp/tsconfig.json index 043c8f7..0462b73 100644 --- a/packages/vite-plugin-cp/tsconfig.json +++ b/packages/vite-plugin-cp/tsconfig.json @@ -1,8 +1,15 @@ { - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": ["src"], - "exclude": ["dist", "node_modules"] - } \ No newline at end of file + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] +} \ No newline at end of file diff --git a/packages/vite-plugin-cp/vite.config.mjs b/packages/vite-plugin-cp/vite.config.mjs new file mode 100644 index 0000000..ca16576 --- /dev/null +++ b/packages/vite-plugin-cp/vite.config.mjs @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = Object.keys(pkg.dependencies) + .map((n) => new RegExp(`^${n}/?`)) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/packages/vite-plugin-external/README.md b/packages/vite-plugin-external/README.md index 13d70f0..b4693fc 100644 --- a/packages/vite-plugin-external/README.md +++ b/packages/vite-plugin-external/README.md @@ -17,12 +17,13 @@ npm install vite-plugin-external --save-dev ## Options -* `enforce?: string` - optional: `'pre' | 'post'` -* `cwd?: string` - default: `process.cwd()` -* `cacheDir?: string` - default: `join(cwd, 'node_modules', '.vite_external')` +* `enforce?: string` - Optional: `'pre' | 'post'` +* `devMode?: string` - Optional: `'development'` +* `cwd?: string` - Default: `process.cwd()` +* `cacheDir?: string` - Default: `${cwd}/node_modules/.vite_external` * `development?: Options` * `production?: Options` -* `externals: [packageName: string]: any` +* `externals: Record` ## Usage @@ -82,4 +83,6 @@ export default defineConfig({ ## Examples -**[Demo](examples/react)** +* [See vite3 demo](../../examples/vite3-external) +* [See vite4 demo](../../examples/vite4-external) +* [See vite5 demo](../../examples/vite5-external) diff --git a/packages/vite-plugin-external/dist/index.cjs b/packages/vite-plugin-external/dist/index.cjs deleted file mode 100644 index 87c5c18..0000000 --- a/packages/vite-plugin-external/dist/index.cjs +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -var node_fs = require('node:fs'); -var fsExtra = require('fs-extra'); -var node_path = require('node:path'); - -// compat cjs and esm -function createCJSExportDeclaration(external) { - return `module.exports = ${external};`; -} -function rollupOutputGlobals(output, externals) { - let { globals } = output; - if (!globals) { - globals = {}; - output.globals = globals; - } - Object.assign(globals, externals); -} -function rollupExternal(rollupOptions, externals, externalKeys) { - let { output, external } = rollupOptions; - if (!output) { - output = {}; - rollupOptions.output = output; - } - // compat Array - if (Array.isArray(output)) { - output.forEach((n) => { - rollupOutputGlobals(n, externals); - }); - } - else { - rollupOutputGlobals(output, externals); - } - // if external indicates - if (!external) { - external = []; - rollupOptions.external = external; - } - external.push(...externalKeys); -} -function createPlugin(opts) { - const cwd = opts.cwd || process.cwd(); - const externalCacheDir = opts.cacheDir || node_path.join(cwd, 'node_modules', '.vite_external'); - let externals = {}; - let externalKeys = []; - let shouldSkip = false; - return { - name: 'vite-plugin-external', - enforce: opts.enforce, - config(config, { mode }) { - const modeOptions = opts[mode]; - externals = Object.assign({}, opts.externals, modeOptions && modeOptions.externals); - externalKeys = Object.keys(externals); - shouldSkip = !externalKeys.length; - if (shouldSkip) { - return; - } - // non development - if (mode !== 'development') { - let { build } = config; - // if no build indicates - if (!build) { - build = {}; - config.build = build; - } - let { rollupOptions } = build; - // if no rollupOptions indicates - if (!rollupOptions) { - rollupOptions = {}; - build.rollupOptions = rollupOptions; - } - rollupExternal(rollupOptions, externals, externalKeys); - return; - } - if (!node_fs.existsSync) { - node_fs.mkdirSync(externalCacheDir); - } - else { - fsExtra.emptyDirSync(externalCacheDir); - } - let { resolve } = config; - if (!resolve) { - resolve = {}; - config.resolve = resolve; - } - let { alias } = resolve; - if (!alias || typeof alias !== 'object') { - alias = []; - resolve.alias = alias; - } - // #1 if alias is object type - if (!Array.isArray(alias)) { - alias = Object.entries(alias).map(([key, value]) => { - return { find: key, replacement: value }; - }); - resolve.alias = alias; - } - for (const libName of externalKeys) { - const libPath = node_path.join(externalCacheDir, `${libName.replace(/\//g, '_')}.js`); - node_fs.writeFileSync(libPath, createCJSExportDeclaration(externals[libName])); - alias.push({ - find: new RegExp(`^${libName}$`), - replacement: libPath - }); - } - } - }; -} - -module.exports = createPlugin; diff --git a/packages/vite-plugin-external/dist/index.d.ts b/packages/vite-plugin-external/dist/index.d.ts index 62594ae..026570f 100644 --- a/packages/vite-plugin-external/dist/index.d.ts +++ b/packages/vite-plugin-external/dist/index.d.ts @@ -1,17 +1,27 @@ import { Plugin } from 'vite'; export interface BasicOptions { - externals?: Externals; -} -export interface Externals { - [packageName: string]: any; -} -export interface Options extends BasicOptions { - [mode: string]: Options | any; + /** + * @default `process.cwd()` + */ cwd?: string; + /** + * @default `${cwd}/node_modules/.vite_external` + */ cacheDir?: string; + externals: Record; +} +export interface Options extends BasicOptions { + [mode: string]: BasicOptions | any; + /** development mode options */ + development?: BasicOptions; + /** production mode options */ + production?: BasicOptions; + devMode?: string; enforce?: 'pre' | 'post'; - externals?: Externals; - development?: Options; - production?: Options; } +/** + * provides a way of excluding dependencies from the runtime code and output bundles. + * @param opts options + * @returns a vite plugin + */ export default function createPlugin(opts: Options): Plugin; diff --git a/packages/vite-plugin-external/dist/index.js b/packages/vite-plugin-external/dist/index.js new file mode 100644 index 0000000..739655e --- /dev/null +++ b/packages/vite-plugin-external/dist/index.js @@ -0,0 +1,117 @@ +"use strict"; +const node_util = require("node:util"); +const fsExtra = require("fs-extra"); +const node_path = require("node:path"); +function get(obj, key) { + if (obj == null) { + return {}; + } + key.split(".").forEach((name) => { + let val = obj[name]; + if (val == null) { + val = {}; + obj[name] = val; + } + obj = val; + }); + return obj; +} +function rollupOutputGlobals(output, externals) { + let { globals } = output; + if (!globals) { + globals = {}; + output.globals = globals; + } + Object.assign(globals, externals); +} +function rollupExternal(rollupOptions, externals, libNames) { + let { output } = rollupOptions; + if (!output) { + output = {}; + rollupOptions.output = output; + } + if (Array.isArray(output)) { + output.forEach((n) => { + rollupOutputGlobals(n, externals); + }); + } else { + rollupOutputGlobals(output, externals); + } + const { external } = rollupOptions; + if (!external) { + rollupOptions.external = libNames; + } else if (typeof external === "string" || node_util.types.isRegExp(external) || Array.isArray(external)) { + rollupOptions.external = libNames.concat(external); + } else if (typeof external === "function") { + rollupOptions.external = function(source, importer, isResolved) { + if (libNames.includes(source)) { + return true; + } + return external(source, importer, isResolved); + }; + } +} +function createFakeLib(globalName, libPath) { + const cjs = `module.exports = ${globalName};`; + return fsExtra.outputFile(libPath, cjs, "utf-8"); +} +function createPlugin(opts) { + return { + name: "vite:external", + enforce: opts.enforce, + async config(config, { mode }) { + let { cwd, cacheDir, externals } = opts; + const modeOptions = opts[mode]; + if (modeOptions) { + Object.entries(modeOptions).forEach(([key, value]) => { + if (value) { + switch (key) { + case "cwd": + cwd = value; + break; + case "cacheDir": + cacheDir = value; + break; + case "externals": + externals = Object.assign({}, externals, value); + break; + } + } + }); + } + if (!cwd) { + cwd = process.cwd(); + } + if (!cacheDir) { + cacheDir = node_path.join(cwd, "node_modules", ".vite_external"); + } + const libNames = !externals ? [] : Object.keys(externals); + const shouldSkip = !libNames.length; + if (shouldSkip) { + return; + } + const devMode = opts.devMode || "development"; + if (mode !== devMode) { + rollupExternal(get(config, "build.rollupOptions"), externals, libNames); + return; + } + fsExtra.emptyDirSync(cacheDir); + let alias = get(config, "resolve.alias"); + if (!Array.isArray(alias)) { + alias = Object.entries(alias).map(([key, value]) => { + return { find: key, replacement: value }; + }); + config.resolve.alias = alias; + } + await Promise.all(libNames.map((libName) => { + const libPath = node_path.join(cacheDir, `${libName.replace(/\//g, "_")}.js`); + alias.push({ + find: new RegExp(`^${libName}$`), + replacement: libPath + }); + return createFakeLib(externals[libName], libPath); + })); + } + }; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-external/dist/index.mjs b/packages/vite-plugin-external/dist/index.mjs index 189f2b6..e5a3f07 100644 --- a/packages/vite-plugin-external/dist/index.mjs +++ b/packages/vite-plugin-external/dist/index.mjs @@ -1,108 +1,118 @@ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; -import { emptyDirSync } from 'fs-extra'; -import { join } from 'node:path'; - -// compat cjs and esm -function createCJSExportDeclaration(external) { - return `module.exports = ${external};`; +import { types } from "node:util"; +import { emptyDirSync, outputFile } from "fs-extra"; +import { join } from "node:path"; +function get(obj, key) { + if (obj == null) { + return {}; + } + key.split(".").forEach((name) => { + let val = obj[name]; + if (val == null) { + val = {}; + obj[name] = val; + } + obj = val; + }); + return obj; } function rollupOutputGlobals(output, externals) { - let { globals } = output; - if (!globals) { - globals = {}; - output.globals = globals; - } - Object.assign(globals, externals); + let { globals } = output; + if (!globals) { + globals = {}; + output.globals = globals; + } + Object.assign(globals, externals); } -function rollupExternal(rollupOptions, externals, externalKeys) { - let { output, external } = rollupOptions; - if (!output) { - output = {}; - rollupOptions.output = output; - } - // compat Array - if (Array.isArray(output)) { - output.forEach((n) => { - rollupOutputGlobals(n, externals); - }); - } - else { - rollupOutputGlobals(output, externals); - } - // if external indicates - if (!external) { - external = []; - rollupOptions.external = external; - } - external.push(...externalKeys); +function rollupExternal(rollupOptions, externals, libNames) { + let { output } = rollupOptions; + if (!output) { + output = {}; + rollupOptions.output = output; + } + if (Array.isArray(output)) { + output.forEach((n) => { + rollupOutputGlobals(n, externals); + }); + } else { + rollupOutputGlobals(output, externals); + } + const { external } = rollupOptions; + if (!external) { + rollupOptions.external = libNames; + } else if (typeof external === "string" || types.isRegExp(external) || Array.isArray(external)) { + rollupOptions.external = libNames.concat(external); + } else if (typeof external === "function") { + rollupOptions.external = function(source, importer, isResolved) { + if (libNames.includes(source)) { + return true; + } + return external(source, importer, isResolved); + }; + } +} +function createFakeLib(globalName, libPath) { + const cjs = `module.exports = ${globalName};`; + return outputFile(libPath, cjs, "utf-8"); } function createPlugin(opts) { - const cwd = opts.cwd || process.cwd(); - const externalCacheDir = opts.cacheDir || join(cwd, 'node_modules', '.vite_external'); - let externals = {}; - let externalKeys = []; - let shouldSkip = false; - return { - name: 'vite-plugin-external', - enforce: opts.enforce, - config(config, { mode }) { - const modeOptions = opts[mode]; - externals = Object.assign({}, opts.externals, modeOptions && modeOptions.externals); - externalKeys = Object.keys(externals); - shouldSkip = !externalKeys.length; - if (shouldSkip) { - return; - } - // non development - if (mode !== 'development') { - let { build } = config; - // if no build indicates - if (!build) { - build = {}; - config.build = build; - } - let { rollupOptions } = build; - // if no rollupOptions indicates - if (!rollupOptions) { - rollupOptions = {}; - build.rollupOptions = rollupOptions; - } - rollupExternal(rollupOptions, externals, externalKeys); - return; - } - if (!existsSync) { - mkdirSync(externalCacheDir); + return { + name: "vite:external", + enforce: opts.enforce, + async config(config, { mode }) { + let { cwd, cacheDir, externals } = opts; + const modeOptions = opts[mode]; + if (modeOptions) { + Object.entries(modeOptions).forEach(([key, value]) => { + if (value) { + switch (key) { + case "cwd": + cwd = value; + break; + case "cacheDir": + cacheDir = value; + break; + case "externals": + externals = Object.assign({}, externals, value); + break; } - else { - emptyDirSync(externalCacheDir); - } - let { resolve } = config; - if (!resolve) { - resolve = {}; - config.resolve = resolve; - } - let { alias } = resolve; - if (!alias || typeof alias !== 'object') { - alias = []; - resolve.alias = alias; - } - // #1 if alias is object type - if (!Array.isArray(alias)) { - alias = Object.entries(alias).map(([key, value]) => { - return { find: key, replacement: value }; - }); - resolve.alias = alias; - } - for (const libName of externalKeys) { - const libPath = join(externalCacheDir, `${libName.replace(/\//g, '_')}.js`); - writeFileSync(libPath, createCJSExportDeclaration(externals[libName])); - alias.push({ - find: new RegExp(`^${libName}$`), - replacement: libPath - }); - } - } - }; + } + }); + } + if (!cwd) { + cwd = process.cwd(); + } + if (!cacheDir) { + cacheDir = join(cwd, "node_modules", ".vite_external"); + } + const libNames = !externals ? [] : Object.keys(externals); + const shouldSkip = !libNames.length; + if (shouldSkip) { + return; + } + const devMode = opts.devMode || "development"; + if (mode !== devMode) { + rollupExternal(get(config, "build.rollupOptions"), externals, libNames); + return; + } + emptyDirSync(cacheDir); + let alias = get(config, "resolve.alias"); + if (!Array.isArray(alias)) { + alias = Object.entries(alias).map(([key, value]) => { + return { find: key, replacement: value }; + }); + config.resolve.alias = alias; + } + await Promise.all(libNames.map((libName) => { + const libPath = join(cacheDir, `${libName.replace(/\//g, "_")}.js`); + alias.push({ + find: new RegExp(`^${libName}$`), + replacement: libPath + }); + return createFakeLib(externals[libName], libPath); + })); + } + }; } - -export { createPlugin as default }; +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-external/package.json b/packages/vite-plugin-external/package.json index 79bf90e..ec068ca 100644 --- a/packages/vite-plugin-external/package.json +++ b/packages/vite-plugin-external/package.json @@ -1,19 +1,21 @@ { "name": "vite-plugin-external", - "version": "4.0.2", + "version": "4.1.0", "description": "Provides a way of excluding dependencies from the runtime code and output bundles.", - "main": "./dist/index.cjs", - "module": "./dist/index.mjs", "types": "./dist/index.d.ts", + "module": "./dist/index.mjs", + "main": "./dist/index.js", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.cjs" + "require": "./dist/index.js" } }, "scripts": { - "build": "rollup --config ./rollup.config.mjs" + "build": "vite build", + "watch": "vite build --watch", + "release": "npm publish" }, "repository": { "type": "git", @@ -32,14 +34,6 @@ "dependencies": { "fs-extra": "^11.1.1" }, - "devDependencies": { - "@rollup/plugin-typescript": "^11.1.3", - "@types/node": "^20.5.9", - "rollup": "^3.28.1", - "rollup-plugin-empty": "^1.0.0", - "rollup-plugin-filesize": "^10.0.0", - "vite": "^4.4.9" - }, "files": [ "dist" ] diff --git a/packages/vite-plugin-external/rollup.config.mjs b/packages/vite-plugin-external/rollup.config.mjs deleted file mode 100644 index 6810656..0000000 --- a/packages/vite-plugin-external/rollup.config.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'rollup'; -import typescript from '@rollup/plugin-typescript'; -import empty from 'rollup-plugin-empty'; -import filesize from 'rollup-plugin-filesize'; - -export default [ - defineConfig({ - input: 'src/index.ts', - plugins: [ - empty({ - dir: 'dist' - }), - typescript({ - tsconfig: './tsconfig.build.json' - }), - filesize() - ], - output: [{ - file: 'dist/index.mjs', - format: 'esm', - exports: 'auto' - }, { - file: 'dist/index.cjs', - format: 'cjs', - exports: 'auto', - externalLiveBindings: false - }] - }) -]; diff --git a/packages/vite-plugin-external/src/index.ts b/packages/vite-plugin-external/src/index.ts index 2d99ecc..57d0da2 100644 --- a/packages/vite-plugin-external/src/index.ts +++ b/packages/vite-plugin-external/src/index.ts @@ -1,34 +1,53 @@ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; -import { emptyDirSync } from 'fs-extra'; +import { types } from 'node:util'; +import { emptyDirSync, outputFile } from 'fs-extra'; import { join } from 'node:path'; import { RollupOptions, OutputOptions } from 'rollup'; import { UserConfig, ConfigEnv, Alias, Plugin } from 'vite'; export interface BasicOptions { - externals?: Externals; -} + /** + * @default `process.cwd()` + */ + cwd?: string; -export interface Externals { - [packageName: string]: any; + /** + * @default `${cwd}/node_modules/.vite_external` + */ + cacheDir?: string; + + externals: Record; } export interface Options extends BasicOptions { - [mode: string]: Options | any; + [mode: string]: BasicOptions | any; - cwd?: string; - cacheDir?: string; + /** development mode options */ + development?: BasicOptions; + + /** production mode options */ + production?: BasicOptions; + + devMode?: string; enforce?: 'pre' | 'post'; - externals?: Externals; - development?: Options; - production?: Options; } -// compat cjs and esm -function createCJSExportDeclaration(external: string) { - return `module.exports = ${external};`; +function get(obj: {[key: string]: any}, key: string): any { + if (obj == null) { + return {}; + } + key.split('.').forEach((name) => { + let val = obj[name]; + if (val == null) { + val = {}; + obj[name] = val; + } + obj = val; + }); + + return obj; } -function rollupOutputGlobals(output: OutputOptions, externals: Externals): void { +function rollupOutputGlobals(output: OutputOptions, externals: Record): void { let { globals } = output; if (!globals) { globals = {}; @@ -37,8 +56,8 @@ function rollupOutputGlobals(output: OutputOptions, externals: Externals): void Object.assign(globals, externals); } -function rollupExternal(rollupOptions: RollupOptions, externals: Externals, externalKeys: string[]): void { - let { output, external } = rollupOptions; +function rollupExternal(rollupOptions: RollupOptions, externals: Record, libNames: any[]): void { + let { output } = rollupOptions; if (!output) { output = {}; rollupOptions.output = output; @@ -54,94 +73,112 @@ function rollupExternal(rollupOptions: RollupOptions, externals: Externals, exte rollupOutputGlobals(output, externals); } + const { external } = rollupOptions; + // if external indicates if (!external) { - external = []; - rollupOptions.external = external; + rollupOptions.external = libNames; + } + // string or RegExp or array + else if (typeof external === 'string' || types.isRegExp(external) || Array.isArray(external)) { + rollupOptions.external = libNames.concat(external); + } + // function + else if (typeof external === 'function') { + rollupOptions.external = function (source: string, importer: string | undefined, isResolved: boolean): + boolean | null | undefined | void { + if (libNames.includes(source)) { + return true; + } + return external(source, importer, isResolved); + }; } - (external as string[]).push(...externalKeys); } -export default function createPlugin(opts: Options): Plugin { - const cwd = opts.cwd || process.cwd(); - const externalCacheDir = opts.cacheDir || join(cwd, 'node_modules', '.vite_external'); - - let externals: Externals = {}; - let externalKeys: string[] = []; - let shouldSkip = false; +// compat cjs and esm +function createFakeLib(globalName: string, libPath: string): Promise { + const cjs = `module.exports = ${globalName};`; + return outputFile(libPath, cjs, 'utf-8'); +} +/** + * provides a way of excluding dependencies from the runtime code and output bundles. + * @param opts options + * @returns a vite plugin + */ +export default function createPlugin(opts: Options): Plugin { return { - name: 'vite-plugin-external', + name: 'vite:external', enforce: opts.enforce, - config(config: UserConfig, { mode }: ConfigEnv) { + async config(config: UserConfig, { mode }: ConfigEnv) { + let { cwd, cacheDir, externals } = opts; const modeOptions: Options | undefined = opts[mode]; - externals = Object.assign({}, opts.externals, modeOptions && modeOptions.externals); - externalKeys = Object.keys(externals); - shouldSkip = !externalKeys.length; - - if (shouldSkip) { - return; + if (modeOptions) { + Object.entries(modeOptions).forEach(([key, value]) => { + if (value) { + switch (key) { + case 'cwd': + cwd = value; + break; + case 'cacheDir': + cacheDir = value; + break; + case 'externals': + externals = Object.assign({}, externals, value); + break; + } + } + }); } - // non development - if (mode !== 'development') { - let { build } = config; - - // if no build indicates - if (!build) { - build = {}; - config.build = build; - } - - let { rollupOptions } = build; + if (!cwd) { + cwd = process.cwd(); + } + if (!cacheDir) { + cacheDir = join(cwd, 'node_modules', '.vite_external'); + } - // if no rollupOptions indicates - if (!rollupOptions) { - rollupOptions = {}; - build.rollupOptions = rollupOptions; - } + const libNames: string[] = !externals ? [] : Object.keys(externals); + const shouldSkip = !libNames.length; - rollupExternal(rollupOptions, externals, externalKeys); + if (shouldSkip) { return; } - if (!existsSync) { - mkdirSync(externalCacheDir); - } - else { - emptyDirSync(externalCacheDir); - } + const devMode = opts.devMode || 'development'; - let { resolve } = config; - if (!resolve) { - resolve = {}; - config.resolve = resolve; + // non development + if (mode !== devMode) { + rollupExternal( + get(config, 'build.rollupOptions'), + externals, + libNames + ); + return; } - let { alias } = resolve; - if (!alias || typeof alias !== 'object') { - alias = []; - resolve.alias = alias; - } + // cleanup cache dir + emptyDirSync(cacheDir); + + let alias = get(config, 'resolve.alias'); // #1 if alias is object type if (!Array.isArray(alias)) { alias = Object.entries(alias).map(([key, value]) => { return { find: key, replacement: value }; }); - resolve.alias = alias; + config.resolve!.alias = alias; } - for (const libName of externalKeys) { - const libPath = join(externalCacheDir, `${libName.replace(/\//g, '_')}.js`); - writeFileSync(libPath, createCJSExportDeclaration(externals[libName])); - + await Promise.all(libNames.map((libName) => { + const libPath = join(cacheDir as string, `${libName.replace(/\//g, '_')}.js`); (alias as Alias[]).push({ find: new RegExp(`^${libName}$`), replacement: libPath }); - } + return createFakeLib(externals[libName], libPath); + })); } }; } diff --git a/packages/vite-plugin-external/tsconfig.build.json b/packages/vite-plugin-external/tsconfig.build.json deleted file mode 100644 index 357ac49..0000000 --- a/packages/vite-plugin-external/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "dist" - } - } \ No newline at end of file diff --git a/packages/vite-plugin-external/tsconfig.json b/packages/vite-plugin-external/tsconfig.json index 043c8f7..0462b73 100644 --- a/packages/vite-plugin-external/tsconfig.json +++ b/packages/vite-plugin-external/tsconfig.json @@ -1,8 +1,15 @@ { - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": ["src"], - "exclude": ["dist", "node_modules"] - } \ No newline at end of file + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] +} \ No newline at end of file diff --git a/packages/vite-plugin-external/vite.config.mjs b/packages/vite-plugin-external/vite.config.mjs new file mode 100644 index 0000000..ca16576 --- /dev/null +++ b/packages/vite-plugin-external/vite.config.mjs @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = Object.keys(pkg.dependencies) + .map((n) => new RegExp(`^${n}/?`)) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/packages/vite-plugin-hook-use/README.md b/packages/vite-plugin-hook-use/README.md new file mode 100644 index 0000000..e178159 --- /dev/null +++ b/packages/vite-plugin-hook-use/README.md @@ -0,0 +1,34 @@ +# vite-plugin-hook-use + +[![npm package](https://nodei.co/npm/vite-plugin-hook-use.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/vite-plugin-hook-use) + +> Display which hooks are used in your project. Vite >= 3.1 + +[![NPM version](https://img.shields.io/npm/v/vite-plugin-hook-use.svg?style=flat)](https://npmjs.org/package/vite-plugin-hook-use) +[![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-hook-use.svg?style=flat)](https://npmjs.org/package/vite-plugin-hook-use) + +![image](https://user-images.githubusercontent.com/6262382/126889725-a5d276ad-913a-4498-8da1-2aa3fd1404ab.png) + +## Installation + +```bash +npm install vite-plugin-hook-use --save-dev +``` + +## Usage + +```js +import createPlugin from 'vite-plugin-hook-use'; + +export default defineConfig({ + plugins: [ + createPlugin() + ] +}); +``` + +## Examples + +* [See vite3 demo](../../examples/vite3-hook-use) +* [See vite4 demo](../../examples/vite4-hook-use) +* [See vite5 demo](../../examples/vite5-hook-use) diff --git a/packages/vite-plugin-hook-use/dist/index.d.ts b/packages/vite-plugin-hook-use/dist/index.d.ts new file mode 100644 index 0000000..e4f9803 --- /dev/null +++ b/packages/vite-plugin-hook-use/dist/index.d.ts @@ -0,0 +1,6 @@ +import { Plugin } from 'vite'; +/** + * Display which hooks are used in your project. + * @returns a vite plugin + */ +export default function createPlugin(): Plugin; diff --git a/packages/vite-plugin-hook-use/dist/index.js b/packages/vite-plugin-hook-use/dist/index.js new file mode 100644 index 0000000..bc1b2ad --- /dev/null +++ b/packages/vite-plugin-hook-use/dist/index.js @@ -0,0 +1,54 @@ +"use strict"; +const prompts = require("@clack/prompts"); +const color = require("picocolors"); +const s = prompts.spinner(); +function createPlugin() { + const order = /* @__PURE__ */ new Map(); + const plugin = [ + // 以下钩子在服务器启动时被调用 + "options", + "buildStart", + // 以下钩子会在每个传入模块请求时被调用 + "resolveId", + "load", + "transform", + // 以下钩子在服务器关闭时被调用 + "buildEnd", + "closeBundle", + // 在开发中不会被调用 + "moduleParsed", + // Vite 独有钩子 + "config", + "configResolved", + "configureServer", + "configurePreviewServer", + "transformIndexHtml", + "handleHotUpdate" + ].reduce((prev, hook) => { + prev[hook] = function() { + order.set(hook, (order.get(hook) || 0) + 1); + }; + return prev; + }, { name: "vite:hook-use" }); + const lastConfig = plugin.config; + plugin.config = function(userConfig, env) { + console.log(color.green(` +env: ${JSON.stringify(env, null, 2)} +`)); + lastConfig(); + }; + const lastCloseBundle = plugin.closeBundle; + plugin.closeBundle = function() { + lastCloseBundle(); + console.log(); + prompts.intro(color.inverse(" === Start === ")); + order.forEach((count, hookName) => { + s.start(); + const text = count === 1 ? hookName : `${hookName}(${count})`; + s.stop(text); + }); + prompts.outro(color.inverse(" === End === ")); + }; + return plugin; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-hook-use/dist/index.mjs b/packages/vite-plugin-hook-use/dist/index.mjs new file mode 100644 index 0000000..0fc3bd6 --- /dev/null +++ b/packages/vite-plugin-hook-use/dist/index.mjs @@ -0,0 +1,55 @@ +import { spinner, intro, outro } from "@clack/prompts"; +import color from "picocolors"; +const s = spinner(); +function createPlugin() { + const order = /* @__PURE__ */ new Map(); + const plugin = [ + // 以下钩子在服务器启动时被调用 + "options", + "buildStart", + // 以下钩子会在每个传入模块请求时被调用 + "resolveId", + "load", + "transform", + // 以下钩子在服务器关闭时被调用 + "buildEnd", + "closeBundle", + // 在开发中不会被调用 + "moduleParsed", + // Vite 独有钩子 + "config", + "configResolved", + "configureServer", + "configurePreviewServer", + "transformIndexHtml", + "handleHotUpdate" + ].reduce((prev, hook) => { + prev[hook] = function() { + order.set(hook, (order.get(hook) || 0) + 1); + }; + return prev; + }, { name: "vite:hook-use" }); + const lastConfig = plugin.config; + plugin.config = function(userConfig, env) { + console.log(color.green(` +env: ${JSON.stringify(env, null, 2)} +`)); + lastConfig(); + }; + const lastCloseBundle = plugin.closeBundle; + plugin.closeBundle = function() { + lastCloseBundle(); + console.log(); + intro(color.inverse(" === Start === ")); + order.forEach((count, hookName) => { + s.start(); + const text = count === 1 ? hookName : `${hookName}(${count})`; + s.stop(text); + }); + outro(color.inverse(" === End === ")); + }; + return plugin; +} +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-hook-use/package.json b/packages/vite-plugin-hook-use/package.json new file mode 100644 index 0000000..ddcadd6 --- /dev/null +++ b/packages/vite-plugin-hook-use/package.json @@ -0,0 +1,42 @@ +{ + "name": "vite-plugin-hook-use", + "version": "4.0.0", + "description": "Display which hooks are used in your project.", + "types": "./dist/index.d.ts", + "module": "./dist/index.mjs", + "main": "./dist/index.js", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } + }, + "scripts": { + "build": "vite build", + "watch": "vite build --watch", + "release": "npm publish" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fengxinming/vite-plugins.git", + "directory": "packages/vite-plugin-external" + }, + "keywords": [ + "vite-plugin", + "vite-plugin-external" + ], + "author": "Jesse Feng ", + "bugs": { + "url": "https://github.com/fengxinming/vite-plugins/issues" + }, + "homepage": "https://github.com/fengxinming/vite-plugins#readme", + "dependencies": { + "@clack/prompts": "^0.7.0", + "fs-extra": "^11.1.1", + "picocolors": "^1.0.0" + }, + "files": [ + "dist" + ] +} diff --git a/packages/vite-plugin-hook-use/src/index.ts b/packages/vite-plugin-hook-use/src/index.ts new file mode 100644 index 0000000..57b1ed6 --- /dev/null +++ b/packages/vite-plugin-hook-use/src/index.ts @@ -0,0 +1,69 @@ +/* eslint-disable no-console */ + +import { Plugin } from 'vite'; +import { + intro, + outro, + spinner +} from '@clack/prompts'; +import color from 'picocolors'; + +const s = spinner(); + +/** + * Display which hooks are used in your project. + * @returns a vite plugin + */ +export default function createPlugin(): Plugin { + const order = new Map(); + + const plugin: Plugin = [ + // 以下钩子在服务器启动时被调用 + 'options', + 'buildStart', + // 以下钩子会在每个传入模块请求时被调用 + 'resolveId', + 'load', + 'transform', + // 以下钩子在服务器关闭时被调用 + 'buildEnd', + 'closeBundle', + // 在开发中不会被调用 + 'moduleParsed', + // Vite 独有钩子 + 'config', + 'configResolved', + 'configureServer', + 'configurePreviewServer', + 'transformIndexHtml', + 'handleHotUpdate' + ].reduce((prev, hook) => { + prev[hook] = function () { + // console.log(color.green(`\n=== Enter hook "${hook}" ===\n`)); + order.set(hook, (order.get(hook) || 0) + 1); + }; + return prev; + }, { name: 'vite:hook-use' }); + + const lastConfig = plugin.config as () => void; + plugin.config = function (userConfig, env) { + console.log(color.green(`\nenv: ${JSON.stringify(env, null, 2)}\n`)); + lastConfig(); + }; + + const lastCloseBundle = plugin.closeBundle as () => void; + plugin.closeBundle = function () { + lastCloseBundle(); + + console.log(); + intro(color.inverse(' === Start === ')); + order.forEach((count, hookName) => { + s.start(); + const text = count === 1 ? hookName : `${hookName}(${count})`; + s.stop(text); + }); + outro(color.inverse(' === End === ')); + }; + + return plugin; +} diff --git a/packages/vite-plugin-hook-use/tsconfig.json b/packages/vite-plugin-hook-use/tsconfig.json new file mode 100644 index 0000000..0462b73 --- /dev/null +++ b/packages/vite-plugin-hook-use/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] +} \ No newline at end of file diff --git a/packages/vite-plugin-hook-use/vite.config.mjs b/packages/vite-plugin-hook-use/vite.config.mjs new file mode 100644 index 0000000..ca16576 --- /dev/null +++ b/packages/vite-plugin-hook-use/vite.config.mjs @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = Object.keys(pkg.dependencies) + .map((n) => new RegExp(`^${n}/?`)) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/packages/vite-plugin-include-css/README.md b/packages/vite-plugin-include-css/README.md index a5d0e15..24a6215 100644 --- a/packages/vite-plugin-include-css/README.md +++ b/packages/vite-plugin-include-css/README.md @@ -24,11 +24,17 @@ export default defineConfig({ ], build: { cssCodeSplit: false, - lib: { - entry: './index.js', - name: 'Foo', - fileName: 'index' + rollupOptions: { + output: { + format: 'iife' + } } } }); ``` + +## Examples + +* [See vite3 demo](../../examples/vite3-include-css) +* [See vite4 demo](../../examples/vite4-include-css) +* [See vite5 demo](../../examples/vite5-include-css) diff --git a/packages/vite-plugin-include-css/dist/index.cjs b/packages/vite-plugin-include-css/dist/index.cjs deleted file mode 100644 index b1a828d..0000000 --- a/packages/vite-plugin-include-css/dist/index.cjs +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -function closure(code) { - return `(function(){${code}})();`; -} -function tryCatch(code) { - return `try{${code}}catch(e){console.error('vite-plugin-inject-css', e);}`; -} -function createStyle(jsCode, cssCode, styleId) { - let newCode = 'var elementStyle = document.createElement(\'style\');' - + `elementStyle.appendChild(document.createTextNode(${JSON.stringify(cssCode)}));` - + 'document.head.appendChild(elementStyle);'; - if (styleId) { - newCode += ` elementStyle.id = "${styleId}"; `; - } - return closure(tryCatch(newCode)) + jsCode; -} -function createPlugin() { - return { - name: 'vite-plugin-include-css', - apply: 'build', - enforce: 'post', - generateBundle(outputOpts, bundle) { - let cssCode = ''; - const cssFileNames = []; - const htmlKeys = []; - // find out all css codes - Object.entries(bundle).forEach(([key, chunk]) => { - if (chunk && chunk.type === 'asset') { - if (chunk.fileName.endsWith('.css')) { - // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - cssCode += chunk.source; - delete bundle[key]; - cssFileNames.push(chunk.fileName); - } - else if (chunk.fileName.endsWith('.html')) { - htmlKeys.push(key); - } - } - }); - cssCode = cssCode.trim(); - if (!cssCode) { - return; - } - // eslint-disable-next-line guard-for-in - for (const key in bundle) { - const chunk = bundle[key]; - // inject css code to js entry - if (chunk && chunk.type === 'chunk' && chunk.isEntry) { - chunk.code = createStyle(chunk.code, cssCode); - break; - } - } - htmlKeys.forEach((key) => { - let html = bundle[key].source; - cssFileNames.forEach((fileName) => { - html = html.replace(new RegExp(``), ''); - }); - bundle[key].source = html; - }); - } - }; -} - -module.exports = createPlugin; diff --git a/packages/vite-plugin-include-css/dist/index.d.ts b/packages/vite-plugin-include-css/dist/index.d.ts index 1a06286..bb3649a 100644 --- a/packages/vite-plugin-include-css/dist/index.d.ts +++ b/packages/vite-plugin-include-css/dist/index.d.ts @@ -1,2 +1,6 @@ import { Plugin } from 'vite'; +/** + * build css into individual js files instead of using css links. + * @returns a vite plugin + */ export default function createPlugin(): Plugin; diff --git a/packages/vite-plugin-include-css/dist/index.js b/packages/vite-plugin-include-css/dist/index.js new file mode 100644 index 0000000..55dd1ab --- /dev/null +++ b/packages/vite-plugin-include-css/dist/index.js @@ -0,0 +1,56 @@ +"use strict"; +function closure(code) { + return `(function(){${code}})();`; +} +function tryCatch(code) { + return `try{${code}}catch(e){console.error('vite-plugin-include-css', e);}`; +} +function createStyle(jsCode, cssCode, styleId) { + let newCode = `var elementStyle = document.createElement('style');elementStyle.appendChild(document.createTextNode(${JSON.stringify(cssCode)}));document.head.appendChild(elementStyle);`; + if (styleId) { + newCode += ` elementStyle.id = "${styleId}"; `; + } + return closure(tryCatch(newCode)) + jsCode; +} +function createPlugin() { + return { + name: "vite-plugin-include-css", + apply: "build", + enforce: "post", + generateBundle(outputOpts, bundle) { + let cssCode = ""; + const cssFileNames = []; + const htmlKeys = []; + Object.entries(bundle).forEach(([key, chunk]) => { + if (chunk && chunk.type === "asset") { + if (chunk.fileName.endsWith(".css")) { + cssCode += chunk.source; + delete bundle[key]; + cssFileNames.push(chunk.fileName); + } else if (chunk.fileName.endsWith(".html")) { + htmlKeys.push(key); + } + } + }); + cssCode = cssCode.trim(); + if (!cssCode) { + return; + } + for (const key in bundle) { + const chunk = bundle[key]; + if (chunk && chunk.type === "chunk" && chunk.isEntry) { + chunk.code = createStyle(chunk.code, cssCode, key.replace(/[./]/g, "_")); + break; + } + } + htmlKeys.forEach((key) => { + let html = bundle[key].source; + cssFileNames.forEach((fileName) => { + html = html.replace(new RegExp(``), ""); + }); + bundle[key].source = html; + }); + } + }; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-include-css/dist/index.mjs b/packages/vite-plugin-include-css/dist/index.mjs index 64e314f..2634ec3 100644 --- a/packages/vite-plugin-include-css/dist/index.mjs +++ b/packages/vite-plugin-include-css/dist/index.mjs @@ -1,63 +1,57 @@ function closure(code) { - return `(function(){${code}})();`; + return `(function(){${code}})();`; } function tryCatch(code) { - return `try{${code}}catch(e){console.error('vite-plugin-inject-css', e);}`; + return `try{${code}}catch(e){console.error('vite-plugin-include-css', e);}`; } function createStyle(jsCode, cssCode, styleId) { - let newCode = 'var elementStyle = document.createElement(\'style\');' - + `elementStyle.appendChild(document.createTextNode(${JSON.stringify(cssCode)}));` - + 'document.head.appendChild(elementStyle);'; - if (styleId) { - newCode += ` elementStyle.id = "${styleId}"; `; - } - return closure(tryCatch(newCode)) + jsCode; + let newCode = `var elementStyle = document.createElement('style');elementStyle.appendChild(document.createTextNode(${JSON.stringify(cssCode)}));document.head.appendChild(elementStyle);`; + if (styleId) { + newCode += ` elementStyle.id = "${styleId}"; `; + } + return closure(tryCatch(newCode)) + jsCode; } function createPlugin() { - return { - name: 'vite-plugin-include-css', - apply: 'build', - enforce: 'post', - generateBundle(outputOpts, bundle) { - let cssCode = ''; - const cssFileNames = []; - const htmlKeys = []; - // find out all css codes - Object.entries(bundle).forEach(([key, chunk]) => { - if (chunk && chunk.type === 'asset') { - if (chunk.fileName.endsWith('.css')) { - // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - cssCode += chunk.source; - delete bundle[key]; - cssFileNames.push(chunk.fileName); - } - else if (chunk.fileName.endsWith('.html')) { - htmlKeys.push(key); - } - } - }); - cssCode = cssCode.trim(); - if (!cssCode) { - return; - } - // eslint-disable-next-line guard-for-in - for (const key in bundle) { - const chunk = bundle[key]; - // inject css code to js entry - if (chunk && chunk.type === 'chunk' && chunk.isEntry) { - chunk.code = createStyle(chunk.code, cssCode); - break; - } - } - htmlKeys.forEach((key) => { - let html = bundle[key].source; - cssFileNames.forEach((fileName) => { - html = html.replace(new RegExp(``), ''); - }); - bundle[key].source = html; - }); + return { + name: "vite-plugin-include-css", + apply: "build", + enforce: "post", + generateBundle(outputOpts, bundle) { + let cssCode = ""; + const cssFileNames = []; + const htmlKeys = []; + Object.entries(bundle).forEach(([key, chunk]) => { + if (chunk && chunk.type === "asset") { + if (chunk.fileName.endsWith(".css")) { + cssCode += chunk.source; + delete bundle[key]; + cssFileNames.push(chunk.fileName); + } else if (chunk.fileName.endsWith(".html")) { + htmlKeys.push(key); + } + } + }); + cssCode = cssCode.trim(); + if (!cssCode) { + return; + } + for (const key in bundle) { + const chunk = bundle[key]; + if (chunk && chunk.type === "chunk" && chunk.isEntry) { + chunk.code = createStyle(chunk.code, cssCode, key.replace(/[./]/g, "_")); + break; } - }; + } + htmlKeys.forEach((key) => { + let html = bundle[key].source; + cssFileNames.forEach((fileName) => { + html = html.replace(new RegExp(``), ""); + }); + bundle[key].source = html; + }); + } + }; } - -export { createPlugin as default }; +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-include-css/package.json b/packages/vite-plugin-include-css/package.json index d7fe4c9..087afce 100644 --- a/packages/vite-plugin-include-css/package.json +++ b/packages/vite-plugin-include-css/package.json @@ -1,45 +1,37 @@ { - "name": "vite-plugin-include-css", - "version": "1.0.2", - "description": "build css into individual js files instead of using css links.", - "main": "./dist/index.cjs", - "module": "./dist/index.mjs", - "types": "./dist/index.d.ts", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs" - } - }, - "scripts": { - "release": "npm publish", - "build": "rollup --config ./rollup.config.mjs" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/fengxinming/vite-plugins.git", - "directory": "packages/vite-plugin-include-css" - }, - "keywords": [ - "vite-plugin", - "vite-plugin-include-css" - ], - "author": "Jesse Feng ", - "bugs": { - "url": "https://github.com/fengxinming/vite-plugins/issues" - }, - "homepage": "https://github.com/fengxinming/vite-plugins#readme", - "devDependencies": { - "@rollup/plugin-typescript": "^11.1.3", - "@types/node": "^20.5.9", - "rollup": "^3.28.1", - "rollup-plugin-empty": "^1.0.0", - "rollup-plugin-filesize": "^10.0.0", - "vite": "^4.4.9" - }, - "files": [ - "dist" - ] -} - \ No newline at end of file + "name": "vite-plugin-include-css", + "version": "4.0.0", + "description": "build css into individual js files instead of using css links.", + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } + }, + "scripts": { + "release": "npm publish", + "build": "vite build", + "watch": "vite build --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fengxinming/vite-plugins.git", + "directory": "packages/vite-plugin-include-css" + }, + "keywords": [ + "vite-plugin", + "vite-plugin-include-css" + ], + "author": "Jesse Feng ", + "bugs": { + "url": "https://github.com/fengxinming/vite-plugins/issues" + }, + "homepage": "https://github.com/fengxinming/vite-plugins#readme", + "files": [ + "dist" + ] +} \ No newline at end of file diff --git a/packages/vite-plugin-include-css/rollup.config.mjs b/packages/vite-plugin-include-css/rollup.config.mjs deleted file mode 100644 index 6810656..0000000 --- a/packages/vite-plugin-include-css/rollup.config.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'rollup'; -import typescript from '@rollup/plugin-typescript'; -import empty from 'rollup-plugin-empty'; -import filesize from 'rollup-plugin-filesize'; - -export default [ - defineConfig({ - input: 'src/index.ts', - plugins: [ - empty({ - dir: 'dist' - }), - typescript({ - tsconfig: './tsconfig.build.json' - }), - filesize() - ], - output: [{ - file: 'dist/index.mjs', - format: 'esm', - exports: 'auto' - }, { - file: 'dist/index.cjs', - format: 'cjs', - exports: 'auto', - externalLiveBindings: false - }] - }) -]; diff --git a/packages/vite-plugin-include-css/src/index.ts b/packages/vite-plugin-include-css/src/index.ts index 2045752..da2e4ef 100644 --- a/packages/vite-plugin-include-css/src/index.ts +++ b/packages/vite-plugin-include-css/src/index.ts @@ -1,11 +1,10 @@ import { Plugin } from 'vite'; - function closure(code: string): string { return `(function(){${code}})();`; } function tryCatch(code: string): string { - return `try{${code}}catch(e){console.error('vite-plugin-inject-css', e);}`; + return `try{${code}}catch(e){console.error('vite-plugin-include-css', e);}`; } function createStyle(jsCode: string, cssCode: string, styleId?: string): string { @@ -19,6 +18,10 @@ function createStyle(jsCode: string, cssCode: string, styleId?: string): string return closure(tryCatch(newCode)) + jsCode; } +/** + * build css into individual js files instead of using css links. + * @returns a vite plugin + */ export default function createPlugin(): Plugin { return { name: 'vite-plugin-include-css', @@ -55,7 +58,7 @@ export default function createPlugin(): Plugin { // inject css code to js entry if (chunk && chunk.type === 'chunk' && chunk.isEntry) { - chunk.code = createStyle(chunk.code, cssCode); + chunk.code = createStyle(chunk.code, cssCode, key.replace(/[./]/g, '_')); break; } } diff --git a/packages/vite-plugin-include-css/tsconfig.build.json b/packages/vite-plugin-include-css/tsconfig.build.json deleted file mode 100644 index 357ac49..0000000 --- a/packages/vite-plugin-include-css/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "dist" - } - } \ No newline at end of file diff --git a/packages/vite-plugin-include-css/tsconfig.json b/packages/vite-plugin-include-css/tsconfig.json index 490c9c0..0462b73 100644 --- a/packages/vite-plugin-include-css/tsconfig.json +++ b/packages/vite-plugin-include-css/tsconfig.json @@ -1,8 +1,15 @@ { - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": ["src"], - "exclude": ["dist", "node_modules"] + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] } \ No newline at end of file diff --git a/packages/vite-plugin-include-css/vite.config.mjs b/packages/vite-plugin-include-css/vite.config.mjs new file mode 100644 index 0000000..a50624a --- /dev/null +++ b/packages/vite-plugin-include-css/vite.config.mjs @@ -0,0 +1,27 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = (pkg.dependencies + ? Object.keys(pkg.dependencies) + .map((n) => new RegExp(`^${n}/?`)) + : []) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/packages/vite-plugin-mock-data/README.md b/packages/vite-plugin-mock-data/README.md index bc627a1..322769c 100644 --- a/packages/vite-plugin-mock-data/README.md +++ b/packages/vite-plugin-mock-data/README.md @@ -16,7 +16,7 @@ npm install vite-plugin-mock-data --save-dev ## Options * `cwd` - Default: `process.cwd()`. -* `isAfter` - If `true`, these mock routes is matched before internal middlewares are installed. +* `isAfter` - If `true`, these mock routes is matched after internal middlewares are installed. * `mockAssetsDir` - Specify the directory to define mock assets. * `mockRouterOptions` - [Initial options of `find-my-way`](https://github.com/delvedor/find-my-way#findmywayoptions) * `mockRoutes` - Initial list of mock routes that should be added to the dev server. @@ -81,10 +81,10 @@ export default defineConfig({ }, '/json': { handler: { hello: 1 } - } + }, '/package.json': { file: './package.json' - }, + } } }) ] @@ -139,7 +139,7 @@ module.exports = { }, '/package.json': { file: './package.json' - }, + } }; ``` @@ -153,4 +153,6 @@ fetch('/package.json') ## Examples -**[See demo](examples/react)** +* [See vite3 demo](../../examples/vite3-mock-data) +* [See vite4 demo](../../examples/vite4-mock-data) +* [See vite5 demo](../../examples/vite5-mock-data) diff --git a/packages/vite-plugin-mock-data/dist/index.cjs b/packages/vite-plugin-mock-data/dist/index.cjs deleted file mode 100644 index 9dedcd5..0000000 --- a/packages/vite-plugin-mock-data/dist/index.cjs +++ /dev/null @@ -1,137 +0,0 @@ -'use strict'; - -var node_path = require('node:path'); -var node_module = require('node:module'); -var node_fs = require('node:fs'); -var globby = require('globby'); -var getRouter = require('find-my-way'); -var vite = require('vite'); -var sirv = require('sirv'); - -function isObject(val) { - return val && typeof val === 'object'; -} -function toAbsolute(pth, cwd) { - return node_path.isAbsolute(pth) - ? pth - : node_path.posix.join(cwd || process.cwd(), pth); -} -function sirvOptions(headers) { - return { - dev: true, - etag: true, - extensions: [], - setHeaders(res, pathname) { - res.setHeader('Access-Control-Allow-Origin', '*'); - if (/\.[tj]sx?$/.test(pathname)) { - res.setHeader('Content-Type', 'application/javascript'); - } - if (headers) { - Object.entries(headers).forEach(([key, val]) => { - if (val) { - res.setHeader(key, val); - } - }); - } - } - }; -} -function configureServer(server, routerOpts, routes, serve, cwd) { - const router = getRouter(routerOpts); - if (Array.isArray(routes)) { - routes.forEach((route) => { - Object.keys(route).forEach((xpath) => { - let [methods, pathname] = xpath.split(' '); - if (!pathname) { - pathname = methods; - methods = 'GET'; - } - let routeConfig = route[xpath]; - if (!isObject(routeConfig)) { - routeConfig = { handler: routeConfig }; - } - let handler; - let store; - if (typeof routeConfig.file === 'string') { - handler = (req, res) => { - const parsedPath = node_path.parse(toAbsolute(routeConfig.file, cwd)); - const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers)); - req.url = `/${parsedPath.base}`; - serve(req, res); - }; - } - else if (typeof routeConfig.handler !== 'function') { - const ret = routeConfig.handler; - const retType = typeof ret; - handler = (req, res) => { - vite.send(req, res, retType !== 'string' ? JSON.stringify(ret) : ret, isObject(ret) ? 'json' : 'html', { - headers: server.config.server.headers - }); - }; - } - else { - handler = routeConfig.handler; - } - if (handler) { - router.on(methods.split('/'), pathname, {}, handler, store); - } - }); - }); - } - if (serve) { - server.middlewares.use(serve); - } - server.middlewares.use((req, res, next) => { - router.defaultRoute = () => next(); - router.lookup(req, res); - }); -} -function createPlugin(opts) { - const { isAfter, mockRouterOptions, mockAssetsDir } = opts; - let { cwd, mockRoutesDir } = opts; - let mockRoutes = (opts.mockRoutes || []); - if (!cwd) { - cwd = process.cwd(); - } - if (isObject(mockRoutes) && !Array.isArray(mockRoutes)) { - mockRoutes = [mockRoutes]; - } - return { - name: 'vite-plugin-mock-data', - async configureServer(server) { - if (mockRoutesDir) { - mockRoutesDir = toAbsolute(mockRoutesDir, cwd); - const paths = await globby(`${mockRoutesDir}/**/*.{js,mjs,json}`); - console.log(paths); - await Promise.all(paths.map((file) => { - return (async () => { - let config; - switch (node_path.extname(file)) { - case '.js': - config = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)))(file); - break; - case '.mjs': - config = (await import(file)).default; - break; - case '.json': - config = JSON.parse(node_fs.readFileSync(file, 'utf-8')); - break; - } - if (config) { - mockRoutes.push(config); - } - })(); - })); - } - let serve = null; - if (mockAssetsDir) { - serve = sirv(toAbsolute(mockAssetsDir, cwd), sirvOptions(server.config.server.headers)); - } - return isAfter - ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd) - : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd); - } - }; -} - -module.exports = createPlugin; diff --git a/packages/vite-plugin-mock-data/dist/index.d.ts b/packages/vite-plugin-mock-data/dist/index.d.ts index a7294c9..5dd65b6 100644 --- a/packages/vite-plugin-mock-data/dist/index.d.ts +++ b/packages/vite-plugin-mock-data/dist/index.d.ts @@ -10,11 +10,28 @@ export interface RouteConfig { [route: string]: string | Handler | HandleRoute; } export interface Options { + /** + * The directory to serve files from. + * @default `process.cwd()` + */ cwd?: string; + /** + * If `true`, these mock routes is matched after internal middlewares are installed. + * @default `false` + */ isAfter?: boolean; + /** Specify the directory to define mock assets. */ mockAssetsDir?: string; + /** Initial options of `find-my-way`. see more at https://github.com/delvedor/find-my-way#findmywayoptions */ mockRouterOptions?: SirvConfig | SirvConfig; + /** Initial list of mock routes that should be added to the dev server. */ mockRoutes?: RouteConfig | RouteConfig[]; + /** Specify the directory to define mock routes that should be added to the dev server. */ mockRoutesDir?: string; } +/** + * Provides a simple way to mock data. + * @param opts Options + * @returns a vite plugin + */ export default function createPlugin(opts: Options): Plugin; diff --git a/packages/vite-plugin-mock-data/dist/index.js b/packages/vite-plugin-mock-data/dist/index.js new file mode 100644 index 0000000..0c7ce99 --- /dev/null +++ b/packages/vite-plugin-mock-data/dist/index.js @@ -0,0 +1,129 @@ +"use strict"; +const node_path = require("node:path"); +const node_module = require("node:module"); +const node_fs = require("node:fs"); +const globby = require("globby"); +const getRouter = require("find-my-way"); +const sirv = require("sirv"); +const vite = require("vite"); +var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null; +function isObject(val) { + return val && typeof val === "object"; +} +function toAbsolute(pth, cwd) { + return node_path.isAbsolute(pth) ? pth : node_path.posix.join(cwd || process.cwd(), pth); +} +function sirvOptions(headers) { + return { + dev: true, + etag: true, + extensions: [], + setHeaders(res, pathname) { + res.setHeader("Access-Control-Allow-Origin", "*"); + if (/\.[tj]sx?$/.test(pathname)) { + res.setHeader("Content-Type", "application/javascript"); + } + if (headers) { + Object.entries(headers).forEach(([key, val]) => { + if (val) { + res.setHeader(key, val); + } + }); + } + } + }; +} +function configureServer(server, routerOpts, routes, serve, cwd) { + const router = getRouter(routerOpts); + if (Array.isArray(routes)) { + routes.forEach((route) => { + Object.keys(route).forEach((xpath) => { + let [methods, pathname] = xpath.split(" "); + if (!pathname) { + pathname = methods; + methods = "GET"; + } + let routeConfig = route[xpath]; + if (!isObject(routeConfig)) { + routeConfig = { handler: routeConfig }; + } + let handler; + if (typeof routeConfig.file === "string") { + handler = (req, res) => { + const parsedPath = node_path.parse(toAbsolute(routeConfig.file, cwd)); + const serve2 = sirv(parsedPath.dir, sirvOptions(server.config.server.headers)); + req.url = `/${parsedPath.base}`; + serve2(req, res); + }; + } else if (typeof routeConfig.handler !== "function") { + const ret = routeConfig.handler; + const retType = typeof ret; + handler = (req, res) => { + vite.send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { + headers: server.config.server.headers + }); + }; + } else { + handler = routeConfig.handler; + } + if (handler) { + router.on(methods.split("/"), pathname, {}, handler, routeConfig.store); + } + }); + }); + } + if (serve) { + server.middlewares.use(serve); + } + server.middlewares.use((req, res, next) => { + router.defaultRoute = () => next(); + router.lookup(req, res); + }); +} +function createPlugin(opts) { + const { isAfter, mockRouterOptions, mockAssetsDir } = opts; + let { cwd, mockRoutesDir } = opts; + let mockRoutes = opts.mockRoutes || []; + if (!cwd) { + cwd = process.cwd(); + } + if (isObject(mockRoutes) && !Array.isArray(mockRoutes)) { + mockRoutes = [mockRoutes]; + } + return { + name: "vite:mock-data", + async configureServer(server) { + if (mockRoutesDir) { + mockRoutesDir = toAbsolute(mockRoutesDir, cwd); + const paths = await globby.globby(`${mockRoutesDir}/**/*.{js,mjs,json}`); + await Promise.all(paths.map((file) => { + return (async () => { + let config; + switch (node_path.extname(file)) { + case ".js": + config = node_module.createRequire(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.src || new URL("index.js", document.baseURI).href)(file); + break; + case ".mjs": + config = (await import(file)).default; + break; + case ".json": + config = JSON.parse(node_fs.readFileSync(file, "utf-8")); + break; + } + if (config) { + mockRoutes.push(config); + } + })(); + })); + } + let serve = null; + if (mockAssetsDir) { + serve = sirv(toAbsolute(mockAssetsDir, cwd), sirvOptions(server.config.server.headers)); + } + if (mockRoutes && mockRoutes.length > 0) { + return isAfter ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd) : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd); + } + } + }; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-mock-data/dist/index.mjs b/packages/vite-plugin-mock-data/dist/index.mjs index 5296142..c6dca09 100644 --- a/packages/vite-plugin-mock-data/dist/index.mjs +++ b/packages/vite-plugin-mock-data/dist/index.mjs @@ -1,135 +1,129 @@ -import { extname, isAbsolute, posix, parse } from 'node:path'; -import { createRequire } from 'node:module'; -import { readFileSync } from 'node:fs'; -import globby from 'globby'; -import getRouter from 'find-my-way'; -import { send } from 'vite'; -import sirv from 'sirv'; - +import { extname, isAbsolute, posix, parse } from "node:path"; +import { createRequire } from "node:module"; +import { readFileSync } from "node:fs"; +import { globby } from "globby"; +import getRouter from "find-my-way"; +import sirv from "sirv"; +import { send } from "vite"; function isObject(val) { - return val && typeof val === 'object'; + return val && typeof val === "object"; } function toAbsolute(pth, cwd) { - return isAbsolute(pth) - ? pth - : posix.join(cwd || process.cwd(), pth); + return isAbsolute(pth) ? pth : posix.join(cwd || process.cwd(), pth); } function sirvOptions(headers) { - return { - dev: true, - etag: true, - extensions: [], - setHeaders(res, pathname) { - res.setHeader('Access-Control-Allow-Origin', '*'); - if (/\.[tj]sx?$/.test(pathname)) { - res.setHeader('Content-Type', 'application/javascript'); - } - if (headers) { - Object.entries(headers).forEach(([key, val]) => { - if (val) { - res.setHeader(key, val); - } - }); - } - } - }; + return { + dev: true, + etag: true, + extensions: [], + setHeaders(res, pathname) { + res.setHeader("Access-Control-Allow-Origin", "*"); + if (/\.[tj]sx?$/.test(pathname)) { + res.setHeader("Content-Type", "application/javascript"); + } + if (headers) { + Object.entries(headers).forEach(([key, val]) => { + if (val) { + res.setHeader(key, val); + } + }); + } + } + }; } function configureServer(server, routerOpts, routes, serve, cwd) { - const router = getRouter(routerOpts); - if (Array.isArray(routes)) { - routes.forEach((route) => { - Object.keys(route).forEach((xpath) => { - let [methods, pathname] = xpath.split(' '); - if (!pathname) { - pathname = methods; - methods = 'GET'; - } - let routeConfig = route[xpath]; - if (!isObject(routeConfig)) { - routeConfig = { handler: routeConfig }; - } - let handler; - let store; - if (typeof routeConfig.file === 'string') { - handler = (req, res) => { - const parsedPath = parse(toAbsolute(routeConfig.file, cwd)); - const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers)); - req.url = `/${parsedPath.base}`; - serve(req, res); - }; - } - else if (typeof routeConfig.handler !== 'function') { - const ret = routeConfig.handler; - const retType = typeof ret; - handler = (req, res) => { - send(req, res, retType !== 'string' ? JSON.stringify(ret) : ret, isObject(ret) ? 'json' : 'html', { - headers: server.config.server.headers - }); - }; - } - else { - handler = routeConfig.handler; - } - if (handler) { - router.on(methods.split('/'), pathname, {}, handler, store); - } + const router = getRouter(routerOpts); + if (Array.isArray(routes)) { + routes.forEach((route) => { + Object.keys(route).forEach((xpath) => { + let [methods, pathname] = xpath.split(" "); + if (!pathname) { + pathname = methods; + methods = "GET"; + } + let routeConfig = route[xpath]; + if (!isObject(routeConfig)) { + routeConfig = { handler: routeConfig }; + } + let handler; + if (typeof routeConfig.file === "string") { + handler = (req, res) => { + const parsedPath = parse(toAbsolute(routeConfig.file, cwd)); + const serve2 = sirv(parsedPath.dir, sirvOptions(server.config.server.headers)); + req.url = `/${parsedPath.base}`; + serve2(req, res); + }; + } else if (typeof routeConfig.handler !== "function") { + const ret = routeConfig.handler; + const retType = typeof ret; + handler = (req, res) => { + send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { + headers: server.config.server.headers }); - }); - } - if (serve) { - server.middlewares.use(serve); - } - server.middlewares.use((req, res, next) => { - router.defaultRoute = () => next(); - router.lookup(req, res); + }; + } else { + handler = routeConfig.handler; + } + if (handler) { + router.on(methods.split("/"), pathname, {}, handler, routeConfig.store); + } + }); }); + } + if (serve) { + server.middlewares.use(serve); + } + server.middlewares.use((req, res, next) => { + router.defaultRoute = () => next(); + router.lookup(req, res); + }); } function createPlugin(opts) { - const { isAfter, mockRouterOptions, mockAssetsDir } = opts; - let { cwd, mockRoutesDir } = opts; - let mockRoutes = (opts.mockRoutes || []); - if (!cwd) { - cwd = process.cwd(); - } - if (isObject(mockRoutes) && !Array.isArray(mockRoutes)) { - mockRoutes = [mockRoutes]; - } - return { - name: 'vite-plugin-mock-data', - async configureServer(server) { - if (mockRoutesDir) { - mockRoutesDir = toAbsolute(mockRoutesDir, cwd); - const paths = await globby(`${mockRoutesDir}/**/*.{js,mjs,json}`); - console.log(paths); - await Promise.all(paths.map((file) => { - return (async () => { - let config; - switch (extname(file)) { - case '.js': - config = createRequire(import.meta.url)(file); - break; - case '.mjs': - config = (await import(file)).default; - break; - case '.json': - config = JSON.parse(readFileSync(file, 'utf-8')); - break; - } - if (config) { - mockRoutes.push(config); - } - })(); - })); + const { isAfter, mockRouterOptions, mockAssetsDir } = opts; + let { cwd, mockRoutesDir } = opts; + let mockRoutes = opts.mockRoutes || []; + if (!cwd) { + cwd = process.cwd(); + } + if (isObject(mockRoutes) && !Array.isArray(mockRoutes)) { + mockRoutes = [mockRoutes]; + } + return { + name: "vite:mock-data", + async configureServer(server) { + if (mockRoutesDir) { + mockRoutesDir = toAbsolute(mockRoutesDir, cwd); + const paths = await globby(`${mockRoutesDir}/**/*.{js,mjs,json}`); + await Promise.all(paths.map((file) => { + return (async () => { + let config; + switch (extname(file)) { + case ".js": + config = createRequire(import.meta.url)(file); + break; + case ".mjs": + config = (await import(file)).default; + break; + case ".json": + config = JSON.parse(readFileSync(file, "utf-8")); + break; } - let serve = null; - if (mockAssetsDir) { - serve = sirv(toAbsolute(mockAssetsDir, cwd), sirvOptions(server.config.server.headers)); + if (config) { + mockRoutes.push(config); } - return isAfter - ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd) - : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd); - } - }; + })(); + })); + } + let serve = null; + if (mockAssetsDir) { + serve = sirv(toAbsolute(mockAssetsDir, cwd), sirvOptions(server.config.server.headers)); + } + if (mockRoutes && mockRoutes.length > 0) { + return isAfter ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd) : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd); + } + } + }; } - -export { createPlugin as default }; +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-mock-data/package.json b/packages/vite-plugin-mock-data/package.json index b69d8db..3ab8d0c 100644 --- a/packages/vite-plugin-mock-data/package.json +++ b/packages/vite-plugin-mock-data/package.json @@ -2,19 +2,20 @@ "name": "vite-plugin-mock-data", "version": "4.0.1", "description": "Provides a simple way to mock data.", - "main": "./dist/index.cjs", + "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.cjs" + "require": "./dist/index.js" } }, "scripts": { "release": "npm publish", - "build": "rollup --config ./rollup.config.mjs" + "build": "vite build", + "watch": "vite build --watch" }, "repository": { "type": "git", @@ -32,18 +33,10 @@ "homepage": "https://github.com/fengxinming/vite-plugins#readme", "dependencies": { "find-my-way": "^7.6.2", - "globby": "^11.1.0", + "globby": "^13.2.2", "sirv": "^2.0.2" }, - "devDependencies": { - "@rollup/plugin-typescript": "^11.1.3", - "@types/node": "^20.5.9", - "rollup": "^3.28.1", - "rollup-plugin-empty": "^1.0.0", - "rollup-plugin-filesize": "^10.0.0", - "vite": "^4.4.9" - }, "files": [ "dist" ] -} +} \ No newline at end of file diff --git a/packages/vite-plugin-mock-data/rollup.config.mjs b/packages/vite-plugin-mock-data/rollup.config.mjs deleted file mode 100644 index 6810656..0000000 --- a/packages/vite-plugin-mock-data/rollup.config.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'rollup'; -import typescript from '@rollup/plugin-typescript'; -import empty from 'rollup-plugin-empty'; -import filesize from 'rollup-plugin-filesize'; - -export default [ - defineConfig({ - input: 'src/index.ts', - plugins: [ - empty({ - dir: 'dist' - }), - typescript({ - tsconfig: './tsconfig.build.json' - }), - filesize() - ], - output: [{ - file: 'dist/index.mjs', - format: 'esm', - exports: 'auto' - }, { - file: 'dist/index.cjs', - format: 'cjs', - exports: 'auto', - externalLiveBindings: false - }] - }) -]; diff --git a/packages/vite-plugin-mock-data/src/index.ts b/packages/vite-plugin-mock-data/src/index.ts index 64fa37d..3088427 100644 --- a/packages/vite-plugin-mock-data/src/index.ts +++ b/packages/vite-plugin-mock-data/src/index.ts @@ -1,11 +1,11 @@ import { isAbsolute, posix, parse, extname } from 'node:path'; import { createRequire } from 'node:module'; import { readFileSync } from 'node:fs'; -import globby from 'globby'; +import { OutgoingHttpHeaders } from 'node:http'; +import { globby } from 'globby'; import getRouter, { Config as SirvConfig, HTTPVersion, HTTPMethod, RouteOptions, Handler } from 'find-my-way'; -import { Plugin, ViteDevServer, send } from 'vite'; import sirv, { RequestHandler, Options as SirvOptions } from 'sirv'; -import { OutgoingHttpHeaders } from 'http'; +import { Plugin, ViteDevServer, send } from 'vite'; export interface HandleRoute { file?: string; @@ -19,11 +19,28 @@ export interface RouteConfig { } export interface Options { + /** + * The directory to serve files from. + * @default `process.cwd()` + */ cwd?: string; + + /** + * If `true`, these mock routes is matched after internal middlewares are installed. + * @default `false` + */ isAfter?: boolean; + + /** Specify the directory to define mock assets. */ mockAssetsDir?: string; + + /** Initial options of `find-my-way`. see more at https://github.com/delvedor/find-my-way#findmywayoptions */ mockRouterOptions?: SirvConfig | SirvConfig; + + /** Initial list of mock routes that should be added to the dev server. */ mockRoutes?: RouteConfig | RouteConfig[]; + + /** Specify the directory to define mock routes that should be added to the dev server. */ mockRoutesDir?: string; } @@ -83,7 +100,6 @@ function configureServer( let handler: Handler | undefined; let opts: RouteOptions | undefined; - let store: any; if (typeof routeConfig.file === 'string') { handler = (req, res) => { @@ -118,7 +134,7 @@ function configureServer( pathname, opts || {}, handler, - store + routeConfig.store ); } }); @@ -135,6 +151,11 @@ function configureServer( }); } +/** + * Provides a simple way to mock data. + * @param opts Options + * @returns a vite plugin + */ export default function createPlugin(opts: Options): Plugin { const { isAfter, @@ -157,14 +178,13 @@ export default function createPlugin(opts: Options): Plugin { } return { - name: 'vite-plugin-mock-data', + name: 'vite:mock-data', async configureServer(server: ViteDevServer) { if (mockRoutesDir) { mockRoutesDir = toAbsolute(mockRoutesDir, cwd); const paths = await globby(`${mockRoutesDir}/**/*.{js,mjs,json}`); - console.log(paths); await Promise.all(paths.map((file) => { return (async () => { let config: RouteConfig | undefined; @@ -194,9 +214,11 @@ export default function createPlugin(opts: Options): Plugin { ); } - return isAfter - ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd as string) - : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd as string); + if (mockRoutes && mockRoutes.length > 0) { + return isAfter + ? () => configureServer(server, mockRouterOptions, mockRoutes, serve, cwd as string) + : configureServer(server, mockRouterOptions, mockRoutes, serve, cwd as string); + } } }; } diff --git a/packages/vite-plugin-mock-data/tsconfig.build.json b/packages/vite-plugin-mock-data/tsconfig.build.json deleted file mode 100644 index 357ac49..0000000 --- a/packages/vite-plugin-mock-data/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "dist" - } - } \ No newline at end of file diff --git a/packages/vite-plugin-mock-data/tsconfig.json b/packages/vite-plugin-mock-data/tsconfig.json index 490c9c0..0462b73 100644 --- a/packages/vite-plugin-mock-data/tsconfig.json +++ b/packages/vite-plugin-mock-data/tsconfig.json @@ -1,8 +1,15 @@ { - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": ["src"], - "exclude": ["dist", "node_modules"] + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] } \ No newline at end of file diff --git a/packages/vite-plugin-mock-data/vite.config.mjs b/packages/vite-plugin-mock-data/vite.config.mjs new file mode 100644 index 0000000..06f4e6a --- /dev/null +++ b/packages/vite-plugin-mock-data/vite.config.mjs @@ -0,0 +1,26 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = Object.keys(pkg.dependencies) + .concat('vite') + .map((n) => new RegExp(`^${n}/?`)) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/packages/vite-plugin-reverse-proxy/README.md b/packages/vite-plugin-reverse-proxy/README.md index 788b467..e5faee0 100644 --- a/packages/vite-plugin-reverse-proxy/README.md +++ b/packages/vite-plugin-reverse-proxy/README.md @@ -2,7 +2,7 @@ [![npm package](https://nodei.co/npm/vite-plugin-reverse-proxy.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/vite-plugin-reverse-proxy) -> Makes the script to be served with the text/javascript MIME type instead of module MIME type. +> Makes the script to be served with the text/javascript MIME type instead of module MIME type. Vite >= 3.1 [![NPM version](https://img.shields.io/npm/v/vite-plugin-reverse-proxy.svg?style=flat)](https://npmjs.org/package/vite-plugin-reverse-proxy) [![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-reverse-proxy.svg?style=flat)](https://npmjs.org/package/vite-plugin-reverse-proxy) @@ -38,7 +38,9 @@ import reverseProxy from 'vite-plugin-reverse-proxy'; export default defineConfig({ plugins: [ reverseProxy({ - '/app.js': 'src/main.jsx' + targets: { + '/app.js':'src/main.jsx' + } }), ] }); @@ -50,4 +52,6 @@ export default defineConfig({ ## Examples -**[See demo](examples/demo-reverse-proxy)** +* [See vite3 demo](../../examples/vite3-reverse-proxy) +* [See vite4 demo](../../examples/vite4-reverse-proxy) +* [See vite5 demo](../../examples/vite5-reverse-proxy) diff --git a/packages/vite-plugin-reverse-proxy/dist/index.d.ts b/packages/vite-plugin-reverse-proxy/dist/index.d.ts new file mode 100644 index 0000000..afe7f63 --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/dist/index.d.ts @@ -0,0 +1,15 @@ +export interface Options { + targets?: Record; + preambleCode?: string; +} +/** + * Makes the script to be served with the text/javascript MIME type instead of module MIME type. + * @param options Options + * @returns a vite plugin + */ +export default function createPlugin(options?: Options): { + name: string; + config(config: any): void; + configResolved(config: any): void; + load(id: any): string | undefined; +}; diff --git a/packages/vite-plugin-reverse-proxy/dist/index.js b/packages/vite-plugin-reverse-proxy/dist/index.js new file mode 100644 index 0000000..bbb281f --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/dist/index.js @@ -0,0 +1,63 @@ +"use strict"; +const path = require("node:path"); +const CLIENT_PUBLIC_PATH = "/@vite/client"; +function moduleScript(base, url, preambleCode) { + let preScript = ""; + const clientCodeScript = ` + + if (!document.getElementById('clientCode')) { + const clientCode = document.createElement('script'); + clientCode.id = 'clientCode'; + clientCode.type = 'module'; + clientCode.src = '${path.posix.join(base, CLIENT_PUBLIC_PATH)}'; + document.head.insertBefore(clientCode, document.head.firstChild); + } + `; + preScript += clientCodeScript; + if (preambleCode) { + const preambleCodeScript = ` +if (!document.getElementById('preambleCode')) { + const preambleCode = document.createElement('script'); + preambleCode.id = 'preambleCode'; + preambleCode.type = 'module'; + preambleCode.appendChild(document.createTextNode(${JSON.stringify(preambleCode.replace("__BASE__", base))})); + document.head.insertBefore(preambleCode, document.getElementById('clientCode')); +} + `; + preScript += preambleCodeScript; + } + return `${preScript} +const mainScript = document.createElement('script'); +mainScript.type = 'module'; +mainScript.src = '${path.posix.join(base, url)}'; +document.body.appendChild(mainScript); + `; +} +function createPlugin(options = {}) { + let devBase = "/"; + let isProduction = true; + const { targets, preambleCode } = options; + return { + name: "vite:reverse-proxy", + config(config) { + devBase = config.base; + }, + configResolved(config) { + isProduction = config.isProduction; + if (!devBase) { + devBase = config.base; + } + }, + load(id) { + if (isProduction || !targets) { + return; + } + const target = targets[id.replace(/(\?|#).*$/, "")]; + if (!target) { + return; + } + return moduleScript(devBase, target, preambleCode); + } + }; +} +module.exports = createPlugin; diff --git a/packages/vite-plugin-reverse-proxy/dist/index.mjs b/packages/vite-plugin-reverse-proxy/dist/index.mjs new file mode 100644 index 0000000..0c28fa0 --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/dist/index.mjs @@ -0,0 +1,64 @@ +import path from "node:path"; +const CLIENT_PUBLIC_PATH = "/@vite/client"; +function moduleScript(base, url, preambleCode) { + let preScript = ""; + const clientCodeScript = ` + + if (!document.getElementById('clientCode')) { + const clientCode = document.createElement('script'); + clientCode.id = 'clientCode'; + clientCode.type = 'module'; + clientCode.src = '${path.posix.join(base, CLIENT_PUBLIC_PATH)}'; + document.head.insertBefore(clientCode, document.head.firstChild); + } + `; + preScript += clientCodeScript; + if (preambleCode) { + const preambleCodeScript = ` +if (!document.getElementById('preambleCode')) { + const preambleCode = document.createElement('script'); + preambleCode.id = 'preambleCode'; + preambleCode.type = 'module'; + preambleCode.appendChild(document.createTextNode(${JSON.stringify(preambleCode.replace("__BASE__", base))})); + document.head.insertBefore(preambleCode, document.getElementById('clientCode')); +} + `; + preScript += preambleCodeScript; + } + return `${preScript} +const mainScript = document.createElement('script'); +mainScript.type = 'module'; +mainScript.src = '${path.posix.join(base, url)}'; +document.body.appendChild(mainScript); + `; +} +function createPlugin(options = {}) { + let devBase = "/"; + let isProduction = true; + const { targets, preambleCode } = options; + return { + name: "vite:reverse-proxy", + config(config) { + devBase = config.base; + }, + configResolved(config) { + isProduction = config.isProduction; + if (!devBase) { + devBase = config.base; + } + }, + load(id) { + if (isProduction || !targets) { + return; + } + const target = targets[id.replace(/(\?|#).*$/, "")]; + if (!target) { + return; + } + return moduleScript(devBase, target, preambleCode); + } + }; +} +export { + createPlugin as default +}; diff --git a/packages/vite-plugin-reverse-proxy/index.d.ts b/packages/vite-plugin-reverse-proxy/index.d.ts deleted file mode 100644 index 26969ee..0000000 --- a/packages/vite-plugin-reverse-proxy/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Plugin } from 'vite'; - -export interface Options { - [propName: string]: any; -} - -export default function createPlugin(options?: Options): Plugin; diff --git a/packages/vite-plugin-reverse-proxy/index.js b/packages/vite-plugin-reverse-proxy/index.js deleted file mode 100644 index 253e210..0000000 --- a/packages/vite-plugin-reverse-proxy/index.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const runtimePublicPath = '/@react-refresh'; -const preambleCode = `import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"; -RefreshRuntime.injectIntoGlobalHook(window); -window.$RefreshReg$ = () => {}; -window.$RefreshSig$ = () => (type) => type; -window.__vite_plugin_react_preamble_installed__ = true;`; - -function moduleScript(base, url, hasReactRefresh) { - // const preambleCodeScript - // = `document.writeln('');`; - - // const mainScript = `document.write('');`; - - let mainScript = ` -const mainScript = document.createElement('script'); -mainScript.type = 'module'; -mainScript.src = '${base}${url}'; -document.body.appendChild(mainScript); - `; - - if (hasReactRefresh) { - const preambleCodeScript = ` - if (!document.getElementById('preambleCode')) { - const preambleCode = document.createElement('script'); - preambleCode.id = 'preambleCode'; - preambleCode.type = 'module'; - preambleCode.appendChild(document.createTextNode(${JSON.stringify(preambleCode.replace('__BASE__', base))})); - document.head.insertBefore(preambleCode,document.head.firstChild); - } - `; - - mainScript = preambleCodeScript + mainScript; - } - - return mainScript; -} - -module.exports = function (mappings = {}) { - let devBase = '/'; - let devMode; - let resolvedConfig; - - return { - name: 'vite:reverse-proxy', - - config(config, { mode }) { - devBase = config.base; - devMode = mode; - }, - - configResolved(config) { - resolvedConfig = config; - }, - - load(id) { - if (devMode === 'development') { - const target = mappings[id.replace(/(\?|#).*$/, '')]; - if (target) { - return moduleScript( - devBase, - target, - !!resolvedConfig.plugins.find((n) => n.name === 'vite:react-refresh') - ); - } - } - } - }; -}; diff --git a/packages/vite-plugin-reverse-proxy/package.json b/packages/vite-plugin-reverse-proxy/package.json index fd01c3e..8dc6037 100644 --- a/packages/vite-plugin-reverse-proxy/package.json +++ b/packages/vite-plugin-reverse-proxy/package.json @@ -1,10 +1,21 @@ { "name": "vite-plugin-reverse-proxy", - "version": "1.0.0", + "version": "4.0.0", "description": "Makes the script to be served with the text/javascript MIME type instead of module MIME type.", - "main": "index.js", + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } + }, "scripts": { - "release": "npm publish" + "release": "npm publish", + "build": "vite build", + "watch": "vite build --watch" }, "repository": { "type": "git", @@ -21,4 +32,4 @@ "url": "https://github.com/fengxinming/vite-plugins/issues" }, "homepage": "https://github.com/fengxinming/vite-plugins#readme" -} +} \ No newline at end of file diff --git a/packages/vite-plugin-reverse-proxy/src/index.ts b/packages/vite-plugin-reverse-proxy/src/index.ts new file mode 100644 index 0000000..50c9444 --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/src/index.ts @@ -0,0 +1,90 @@ +import path from 'node:path'; + +const CLIENT_PUBLIC_PATH = '/@vite/client'; + +function moduleScript(base: string, url: string, preambleCode?: string) { + let preScript = ''; + + const clientCodeScript = ` + + if (!document.getElementById('clientCode')) { + const clientCode = document.createElement('script'); + clientCode.id = 'clientCode'; + clientCode.type = 'module'; + clientCode.src = '${path.posix.join(base, CLIENT_PUBLIC_PATH)}'; + document.head.insertBefore(clientCode, document.head.firstChild); + } + `; + + preScript += clientCodeScript; + + if (preambleCode) { + const preambleCodeScript = ` +if (!document.getElementById('preambleCode')) { + const preambleCode = document.createElement('script'); + preambleCode.id = 'preambleCode'; + preambleCode.type = 'module'; + preambleCode.appendChild(document.createTextNode(${JSON.stringify(preambleCode.replace('__BASE__', base))})); + document.head.insertBefore(preambleCode, document.getElementById('clientCode')); +} + `; + + preScript += preambleCodeScript; + } + + return `${preScript} +const mainScript = document.createElement('script'); +mainScript.type = 'module'; +mainScript.src = '${path.posix.join(base, url)}'; +document.body.appendChild(mainScript); + `; +} + +export interface Options { + targets?: Record; + preambleCode?: string; +} + +/** + * Makes the script to be served with the text/javascript MIME type instead of module MIME type. + * @param options Options + * @returns a vite plugin + */ +export default function createPlugin(options: Options = {}) { + let devBase = '/'; + let isProduction = true; + + const { targets, preambleCode } = options; + + return { + name: 'vite:reverse-proxy', + + config(config) { + devBase = config.base; + }, + + configResolved(config) { + isProduction = config.isProduction; + if (!devBase) { + devBase = config.base; + } + }, + + load(id) { + if (isProduction || !targets) { + return; + } + + const target = targets[id.replace(/(\?|#).*$/, '')]; + if (!target) { + return; + } + + return moduleScript( + devBase, + target, + preambleCode + ); + } + }; +} diff --git a/packages/vite-plugin-reverse-proxy/tsconfig.json b/packages/vite-plugin-reverse-proxy/tsconfig.json new file mode 100644 index 0000000..0462b73 --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "dist", + "stripInternal": true + }, + "include": [ + "src" + ], + "exclude": [ + "dist", + "node_modules" + ] +} \ No newline at end of file diff --git a/packages/vite-plugin-reverse-proxy/vite.config.mjs b/packages/vite-plugin-reverse-proxy/vite.config.mjs new file mode 100644 index 0000000..a50624a --- /dev/null +++ b/packages/vite-plugin-reverse-proxy/vite.config.mjs @@ -0,0 +1,27 @@ +import { defineConfig } from 'vite'; +import ts from '@rollup/plugin-typescript'; +import pkg from './package.json'; + +const externals = (pkg.dependencies + ? Object.keys(pkg.dependencies) + .map((n) => new RegExp(`^${n}/?`)) + : []) + .concat(/^node:/); + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + ts() + ], + build: { + lib: { + entry: 'src/index.ts', + formats: ['es', 'cjs'], + fileName: 'index' + }, + minify: false, + rollupOptions: { + external: externals + } + } +}); diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml deleted file mode 100644 index ed54ecd..0000000 --- a/pnpm-workspace.yaml +++ /dev/null @@ -1,3 +0,0 @@ -packages: - - 'packages/*' - - 'examples/*' \ No newline at end of file diff --git a/tsconfig.base.json b/tsconfig.base.json index 8e3f886..3f78311 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -1,29 +1,29 @@ { - "compilerOptions": { - "baseUrl": ".", - "sourceMap": false, - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "node", - "newLine": "LF", - "strict": true, - - "allowJs": true, - "noImplicitAny": false, - "noImplicitThis": false, - - "downlevelIteration": true, - "noUnusedLocals": true, - "experimentalDecorators": true, - "resolveJsonModule": true, - "esModuleInterop": true, - "removeComments": false, - "jsx": "preserve", - "lib": ["esnext", "dom"], - "types": ["node"], - - "declaration": true - }, - "exclude": ["node_modules"] -} - \ No newline at end of file + "compilerOptions": { + "baseUrl": ".", + "sourceMap": false, + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "node", + "newLine": "LF", + "strict": true, + + "allowJs": true, + "noImplicitAny": false, + "noImplicitThis": false, + + "noUnusedLocals": true, + "experimentalDecorators": true, + "resolveJsonModule": true, + "isolatedModules": true, + "skipLibCheck": true, + "esModuleInterop": true, + "removeComments": false, + "jsx": "preserve", + "lib": ["esnext", "dom"], + "types": ["node"] + }, + "exclude": [ + "node_modules" + ] +} \ No newline at end of file diff --git a/tsconfig.typedoc.json b/tsconfig.typedoc.json new file mode 100644 index 0000000..8fb6f31 --- /dev/null +++ b/tsconfig.typedoc.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "include": [ + "packages" + ] +} \ No newline at end of file diff --git a/typedoc.json b/typedoc.json new file mode 100644 index 0000000..cfb3445 --- /dev/null +++ b/typedoc.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "entryPoints": [ + "packages/*/src/index.ts" + ], + "out": "docs", + "tsconfig": "./tsconfig.typedoc.json", + "htmlLang": "en-US", + "readme": "api.md" +} \ No newline at end of file