vuepress / core

Vue-Powered Static Site Generator
https://vuepress.vuejs.org
MIT License
2.26k stars 925 forks source link

SSR not working with ESM modules in vite #585

Closed hschaefer123 closed 2 years ago

hschaefer123 commented 2 years ago

Bug report

After updating deps of btp.udina.de live with 2.0.0.beta27 i run into some issues.

Description

Fomerly, i did no need ClientOnly tags around my custom components loaded by plugin register-components, but i was able to fix this using

<ClientOnly>MyCmpCMP</ClientOnly>

Somehow, using vuepress dev docs the site is not working in browser. If i open chrome dev tools, i see errors, but on reload, preview is working?!?

Some of the used Components (referencing UI5 Web Component) initially throw an error

[vite] Something unexpected happened while optimizing "/service/udina/pricing.html"
The current page should have reloaded by now

Then i manually have to reload the page 1/2 times, to get the component working in preview?

After serving the site multiple times, i am able to preview the whole site and i wantz to compile the result. Problem: Event not used artefacts are throwing errors (wrong images, etc.) but they are not linked/used in config. Anyhow, this worked with older version.

Now trying to build the docs using vuepress build docs --clean-cache

✖ Rendering pages - failed
Error: Cannot find module 'C:\VSC\@udina\udina.docng\node_modules\@ui5\webcomponents\dist\Label'
    at createEsmNotFoundErr (internal/modules/cjs/loader.js:916:15)
    at finalizeEsmResolution (internal/modules/cjs/loader.js:909:15)
    at resolveExports (internal/modules/cjs/loader.js:449:14)
    at Function.Module._findPath (internal/modules/cjs/loader.js:489:31)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:875:27)
    at Function.Module._load (internal/modules/cjs/loader.js:745:27)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Module.<anonymous> (C:\VSC\@udina\udina.docng\site\.server\app.js:30:1)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)

There seems to be some issues with vite and custom components.

Maybe this is a problem with plugin-register-components. All Component are inside -> /docs/.vuepress/components/...

The import import "@ui5/webcomponents/dist/Label"; is referencing the devDependencies

"devDependencies": {  
   "@ui5/webcomponents": "^1.0.2"
}

and is also available.

Additionally using config option

  bundlerConfig: {
    vue: {
      compilerOptions: {
        isCustomElement: (tag) => /^ui5-/.test(tag)
      }
    }
  }

Environment info

Just figured out, that i can fallback to webpack and everthing is still working as expected. But anyhow, since vite is the new default, maybe this issues are solveable also on vite.

Best Regards Holger

meteorlxy commented 2 years ago

We have switch the default bundler to vite since v2.0.0-beta.28. Your bundlerConfig is for webpack.

Try migrating bundlerConfig.vue.compilerOptions to bundlerConfig.vuePluginOptions.template.compilerOptions

github-actions[bot] commented 2 years ago

This issue is marked as stale because it has not had recent activity. Issues marked with stale will be closed if they have no activity within 3 days.

hschaefer123 commented 2 years ago

Hi, i just found the time to update to beta32 and apply your settings.

I applied the vite compiler options, but i was only able to get rid of the console.logs for the web components namespace.

I just did a fresh install and always got the error

clientAppSetup.js?t=1640938795483:7 Uncaught ReferenceError: Cannot access 'defineClientAppSetup' before initialization
    at clientAppSetup.js?t=1640938795483:7

inside @vuepress/plugin-active-header-links/lib/client/clientAppSetup.js?t=1640938795483

If i then reload, the issue has been gone.

Also, using vite and webcomponents, vite is somehow restarting multiple times on console. I was using the dev server with option --clean-cache which seems to be contra productive.

Still my main problem is, that i am not able to build the site, while preview is working.

info Initializing VuePress and preparing data...
✔ Compiling with vite - done
✖ Rendering pages - failed
C:\VSC\playground\vuepress-next\node_modules\@ui5\webcomponents-base\dist\config\Theme.js:1
import { getTheme as getConfiguredTheme } from "../InitialConfiguration.js";
^^^^^^

SyntaxError: Cannot use import statement outside a module

I was able to get rid of this error adding "type": "module", to package.json

But next error is

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\VSC\playground\vuepress-next\docs\.vuepress\dist\.server\app.js

I like the performance of vite, but webpack worked out-of-the-box for me.

Since preview is working, it would be great to get all the dependencies also working for the build.

Anyhow, webpack is my current working option, and if this will be supported also in the future, i can stay on this.

I just wanted to give feedback ;-)

Best Regards Holger

Mister-Hope commented 2 years ago

I met similar issues when using pure esm packages on client side with vite.

I am importing screenfull@v6 (esm) with import screenfull from 'screenfull' on client side, and webpack just works fine, while vite starts yewling the following issues after upgradeing to beta.32

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\projects\vuepress-theme-hope\node_modules\screenfull\index.js from C:\projects\vuepress-theme-hope\demo\src\.vuepress\dist\.server\app.js not supported.
Instead change the require of index.js in C:\projects\vuepress-theme-hope\demo\src\.vuepress\dist\.server\app.js to a dynamic import() which is available in all CommonJS modules.
    at Module.<anonymous> (C:\projects\vuepress-theme-hope\demo\src\.vuepress\dist\.server\app.js:29:11)
    at C:\projects\vuepress-theme-hope\node_modules\@vuepress\bundler-vite\lib\build\createBuild.js:39:34
    at async C:\projects\vuepress-theme-hope\node_modules\@vuepress\utils\lib\withSpinner.js:12:24
    at async Object.build (C:\projects\vuepress-theme-hope\node_modules\@vuepress\bundler-vite\lib\build\createBuild.js:30:5)
    at async C:\projects\vuepress-theme-hope\node_modules\@vuepress\cli\lib\commands\build\createBuild.js:49:5

BTW I updgrade this deps months ago, and it's working fine on vite that time either.

May need some help here. @meteorlxy I think there might be some issues generating this file which leads "requiring" esm modules in the generated code (I guess?)

// dist/.server/app.js:29
var w$4 = require("screenfull");
DerYeger commented 2 years ago

I'm having the exact same issue with d3 (and its packages like d3-selection). Preview works fine, but the build fails with ERR_REQUIRE_ESM.

Logs of the issue are available at https://github.com/DerYeger/d3-graph-controller/runs/4744365874?check_suite_focus=true.

While Webpack does work, it has other issues like broken CSS. I'd much prefer to stay with Vite.

Mister-Hope commented 2 years ago

Any plan to fix it? @meteorlxy

I prefer to regard it as a critical bug. Since vite is the default bundler, as long as there are any pure esm packages imported on the client side, vite will fail on built.

Mister-Hope commented 2 years ago

🙂 It would be nice to have this fixed soon.

I am really tired explaining to users why vite is not working in my plugin(it's the default bundler now), and becaue of this bug, I have to downgrade all the deps to cjs versions.

Mister-Hope commented 2 years ago

@meteorlxy I finally figure out the problem location.

A list of package is hard code here.

https://github.com/vuepress/vuepress-next/blob/73d297f321750de098c22c8c774dbe934475ddcb/packages/%40vuepress/bundler-vite/src/plugins/createMainPlugin.ts#L9-L33

But actually packages having client esm and node cjs should also be posted above so that they can be resolved here.

https://github.com/vuepress/vuepress-next/blob/73d297f321750de098c22c8c774dbe934475ddcb/packages/%40vuepress/bundler-vite/src/plugins/createMainPlugin.ts#L107-L109

When I add my package here in the list, I sucessfully built with vite, but without my package in the list, I am getting:

> vuepress-theme-hope-project@2.0.0 docs:build
> vuepress build src

info Initializing VuePress and preparing data...
⠼ Compiling with vite
(!) Some chunks are larger than 500 KiB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.
✔ Compiling with vite - done
✖ Rendering pages - failed
/home/user/vue2test/node_modules/@mr-hope/vuepress-shared/lib/client/index.js:1
import{defineComponent as t,h as e,computed as n}from"vue";import{useRouteLocale as r,usePageData as i}from"@vuepress/client";import"./styles/message.scss";const s=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,o=t=>`${t.charAt(0).toUpperCase()}${t.slice(1).toLowerCase()}`;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var a,u={exports:{}},c=u.exports=function(){var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",o="hour",a="day",u="week",c="month",f="quarter",d="year",h="date",l="Invalid Date",m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,$=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")},p=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},y={s:p,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+p(r,2,"0")+":"+p(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,o=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-o:o-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:d,w:u,d:a,D:h,h:o,m:s,s:i,ms:r,Q:f}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},g="en",M={};M[g]=v;var D=function(t){return t instanceof w},_=function(t,e,n){var r;if(!t)return g;if("string"==typeof t)M[t]&&(r=t),e&&(M[t]=e,r=t);else{var i=t.name;M[i]=t,r=i}return!n&&r&&(g=r),r||!n&&g},Y=function(t,e){if(D(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new w(n)},S=y;S.l=_,S.i=D,S.w=function(t,e){return Y(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var w=function(){function v(t){this.$L=_(t.locale,null,!0),this.parse(t)}var p=v.prototype;return p.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(S.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match(m);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},p.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},p.$utils=function(){return S},p.isValid=function(){return!(this.$d.toString()===l)},p.isSame=function(t,e){var n=Y(t);return this.startOf(e)<=n&&n<=this.endOf(e)},p.isAfter=function(t,e){return Y(t)<this.startOf(e)},p.isBefore=function(t,e){return this.endOf(e)<Y(t)},p.$g=function(t,e,n){return S.u(t)?this[e]:this.set(n,t)},p.unix=function(){return Math.floor(this.valueOf()/1e3)},p.valueOf=function(){return this.$d.getTime()},p.startOf=function(t,e){var n=this,r=!!S.u(e)||e,f=S.p(t),l=function(t,e){var i=S.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},m=function(t,e){return S.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},$=this.$W,v=this.$M,p=this.$D,y="set"+(this.$u?"UTC":"");switch(f){case d:return r?l(1,0):l(31,11);case c:return r?l(1,v):l(0,v+1);case u:var g=this.$locale().weekStart||0,M=($<g?$+7:$)-g;return l(r?p-M:p+(6-M),v);case a:case h:return m(y+"Hours",0);case o:return m(y+"Minutes",1);case s:return m(y+"Seconds",2);case i:return m(y+"Milliseconds",3);default:return this.clone()}},p.endOf=function(t){return this.startOf(t,!1)},p.$set=function(t,e){var n,u=S.p(t),f="set"+(this.$u?"UTC":""),l=(n={},n[a]=f+"Date",n[h]=f+"Date",n[c]=f+"Month",n[d]=f+"FullYear",n[o]=f+"Hours",n[s]=f+"Minutes",n[i]=f+"Seconds",n[r]=f+"Milliseconds",n)[u],m=u===a?this.$D+(e-this.$W):e;if(u===c||u===d){var $=this.clone().set(h,1);$.$d[l](m),$.init(),this.$d=$.set(h,Math.min(this.$D,$.daysInMonth())).$d}else l&&this.$d[l](m);return this.init(),this},p.set=function(t,e){return this.clone().$set(t,e)},p.get=function(t){return this[S.p(t)]()},p.add=function(r,f){var h,l=this;r=Number(r);var m=S.p(f),$=function(t){var e=Y(l);return S.w(e.date(e.date()+Math.round(t*r)),l)};if(m===c)return this.set(c,this.$M+r);if(m===d)return this.set(d,this.$y+r);if(m===a)return $(1);if(m===u)return $(7);var v=(h={},h[s]=e,h[o]=n,h[i]=t,h)[m]||1,p=this.$d.getTime()+r*v;return S.w(p,this)},p.subtract=function(t,e){return this.add(-1*t,e)},p.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=S.z(this),s=this.$H,o=this.$m,a=this.$M,u=n.weekdays,c=n.months,f=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].substr(0,s)},d=function(t){return S.s(s%12||12,t,"0")},h=n.meridiem||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r},m={YY:String(this.$y).slice(-2),YYYY:this.$y,M:a+1,MM:S.s(a+1,2,"0"),MMM:f(n.monthsShort,a,c,3),MMMM:f(c,a),D:this.$D,DD:S.s(this.$D,2,"0"),d:String(this.$W),dd:f(n.weekdaysMin,this.$W,u,2),ddd:f(n.weekdaysShort,this.$W,u,3),dddd:u[this.$W],H:String(s),HH:S.s(s,2,"0"),h:d(1),hh:d(2),a:h(s,o,!0),A:h(s,o,!1),m:String(o),mm:S.s(o,2,"0"),s:String(this.$s),ss:S.s(this.$s,2,"0"),SSS:S.s(this.$ms,3,"0"),Z:i};return r.replace($,(function(t,e){return e||m[t]||i.replace(":","")}))},p.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},p.diff=function(r,h,l){var m,$=S.p(h),v=Y(r),p=(v.utcOffset()-this.utcOffset())*e,y=this-v,g=S.m(this,v);return g=(m={},m[d]=g/12,m[c]=g,m[f]=g/3,m[u]=(y-p)/6048e5,m[a]=(y-p)/864e5,m[o]=y/n,m[s]=y/e,m[i]=y/t,m)[$]||y,l?g:S.a(g)},p.daysInMonth=function(){return this.endOf(c).$D},p.$locale=function(){return M[this.$L]},p.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=_(t,e,!0);return r&&(n.$L=r),n},p.clone=function(){return S.w(this.$d,this)},p.toDate=function(){return new Date(this.valueOf())},p.toJSON=function(){return this.isValid()?this.toISOString():null},p.toISOString=function(){return this.$d.toISOString()},p.toString=function(){return this.$d.toUTCString()},v}(),O=w.prototype;return Y.prototype=O,[["$ms",r],["$s",i],["$m",s],["$H",o],["$W",a],["$M",c],["$y",d],["$D",h]].forEach((function(t){O[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),Y.extend=function(t,e){return t.$i||(t(e,w,Y),t.$i=!0),Y},Y.locale=_,Y.isDayjs=D,Y.unix=function(t){return Y(1e3*t)},Y.en=M[g],Y.Ls=M,Y.p={},Y}(),f={exports:{}},d=f.exports=(a={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},function(t,e,n){var r=e.prototype,i=r.format;n.en.formats=a,r.format=function(t){void 0===t&&(t="YYYY-MM-DDTHH:mm:ssZ");var e=this.$locale().formats,n=function(t,e){return t.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var i=r&&r.toUpperCase();return n||e[r]||a[r]||e[i].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(t,e,n){return e||n.slice(1)}))}))}(t,void 0===e?{}:e);return i.call(this,n)}}),h={exports:{}},l=h.exports=function(t,e,n){var r=e.prototype,i=function(t){var e,i=t.date,s=t.utc,o={};if(!((e=i)instanceof Date)&&!(e instanceof Array)&&e instanceof Object){if(!Object.keys(i).length)return new Date;var a=s?n.utc():n();Object.keys(i).forEach((function(t){var e,n;o[(e=t,n=r.$utils().p(e),"date"===n?"day":n)]=i[t]}));var u=o.day||(o.year||o.month>=0?1:a.date()),c=o.year||a.year(),f=o.month>=0?o.month:o.year||o.day?0:a.month(),d=o.hour||0,h=o.minute||0,l=o.second||0,m=o.millisecond||0;return s?new Date(Date.UTC(c,f,u,d,h,l,m)):new Date(c,f,u,d,h,l,m)}return i},s=r.parse;r.parse=function(t){t.date=i.bind(this)(t),s.bind(this)(t)};var o=r.set,a=r.add,u=function(t,e,n,r){if(void 0===r&&(r=1),e instanceof Object){var i=Object.keys(e),s=this;return i.forEach((function(n){s=t.bind(s)(e[n]*r,n)})),s}return t.bind(this)(e*r,n)};r.set=function(t,e){return e=void 0===e?t:e,u.bind(this)((function(t,e){return o.bind(this)(e,t)}),e,t)},r.add=function(t,e){return u.bind(this)(a,t,e)},r.subtract=function(t,e){return u.bind(this)(a,t,e,-1)}},m={exports:{}},$=m.exports=function(){var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,r,i){var s,o=function(t,n,r){void 0===r&&(r={});var i=new Date(t);return function(t,n){void 0===n&&(n={});var r=n.timeZoneName||"short",i=t+"|"+r,s=e[i];return s||(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:r}),e[i]=s),s}(n,r).formatToParts(i)},a=function(e,n){for(var r=o(e,n),s=[],a=0;a<r.length;a+=1){var u=r[a],c=u.type,f=u.value,d=t[c];d>=0&&(s[d]=parseInt(f,10))}var h=s[3],l=24===h?0:h,m=s[0]+"-"+s[1]+"-"+s[2]+" "+l+":"+s[4]+":"+s[5]+":000",$=+e;return(i.utc(m).valueOf()-($-=$%1e3))/6e4},u=r.prototype;u.tz=function(t,e){void 0===t&&(t=s);var n=this.utcOffset(),r=this.toDate(),o=r.toLocaleString("en-US",{timeZone:t}),a=Math.round((r-new Date(o))/1e3/60),u=i(o).$set("millisecond",this.$ms).utcOffset(15*-Math.round(r.getTimezoneOffset()/15)-a,!0);if(e){var c=u.utcOffset();u=u.add(n-c,"minute")}return u.$x.$timezone=t,u},u.offsetName=function(t){var e=this.$x.$timezone||i.tz.guess(),n=o(this.valueOf(),e,{timeZoneName:t}).find((function(t){return"timezonename"===t.type.toLowerCase()}));return n&&n.value};var c=u.startOf;u.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return c.call(this,t,e);var n=i(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return c.call(n,t,e).tz(this.$x.$timezone,!0)},i.tz=function(t,e,n){var r=n&&e,o=n||e||s,u=a(+i(),o);if("string"!=typeof t)return i(t).tz(o);var c=function(t,e,n){var r=t-60*e*1e3,i=a(r,n);if(e===i)return[r,e];var s=a(r-=60*(i-e)*1e3,n);return i===s?[r,i]:[t-60*Math.min(i,s)*1e3,Math.max(i,s)]}(i.utc(t,r).valueOf(),u,o),f=c[0],d=c[1],h=i(f).utcOffset(d);return h.$x.$timezone=o,h},i.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},i.tz.setDefault=function(t){s=t}}}(),v={exports:{}},p=v.exports=function(){var t="minute",e=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(r,i,s){var o=i.prototype;s.utc=function(t){return new i({date:t,utc:!0,args:arguments})},o.utc=function(e){var n=s(this.toDate(),{locale:this.$L,utc:!0});return e?n.add(this.utcOffset(),t):n},o.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var a=o.parse;o.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),a.call(this,t)};var u=o.init;o.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else u.call(this)};var c=o.utcOffset;o.utcOffset=function(r,i){var s=this.$utils().u;if(s(r))return this.$u?0:s(this.$offset)?c.call(this):this.$offset;if("string"==typeof r&&null===(r=function(t){void 0===t&&(t="");var r=t.match(e);if(!r)return null;var i=(""+r[0]).match(n)||["-",0,0],s=i[0],o=60*+i[1]+ +i[2];return 0===o?0:"+"===s?o:-o}(r)))return this;var o=Math.abs(r)<=16?60*r:r,a=this;if(i)return a.$offset=o,a.$u=0===r,a;if(0!==r){var u=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(o+u,t)).$offset=o,a.$x.$localOffset=u}else a=this.utc();return a};var f=o.format;o.format=function(t){var e=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return f.call(this,e)},o.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||(new Date).getTimezoneOffset());return this.$d.valueOf()-6e4*t},o.isUTC=function(){return!!this.$u},o.toISOString=function(){return this.toDate().toISOString()},o.toString=function(){return this.toDate().toUTCString()};var d=o.toDate;o.toDate=function(t){return"s"===t&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var h=o.diff;o.diff=function(t,e,n){if(t&&this.$u===t.$u)return h.call(this,t,e,n);var r=this.local(),i=s(t).local();return h.call(r,i,e,n)}}}();c.extend(d),c.extend(l),c.extend(p),c.extend($);const y={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:(t,e)=>"W"===e?`${t}周`:`${t}日`,weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:(t,e)=>{const n=100*t+e;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}},g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")};c.locale("zh",y),c.locale("en",g);const M=c,D=(t,e={})=>{const{lang:n,timezone:r,type:i}=e;M.locale(((t="en")=>{const e=t.toLowerCase();return"zh"===e||"zh-cn"===e?"zh":("en-us"===e||"en-uk"===e||"en"===e||console.warn(`${t} locale missing in config`),"en")})(n));const s=r?M(t).tz(r).format("LL"):M(t).format("LL"),o=r?M(t).tz(r).format("HH:mm"):M(t).format("HH:mm");return"date"===i?s:"time"===i?o:`${s} ${o}`},_=(t,e={})=>{const{timezone:n}=e;if(t){if(M(t instanceof Date?t:t.trim()).isValid()){const r=n?M(t).tz(n):M(t),i=r.year(),s=r.month()+1,o=r.date(),a=r.hour(),u=r.minute(),c=r.second(),f=r.millisecond(),d=0===a&&0===u&&0===c&&0===f,h=r.toDate();return{display:D(h,{type:d?"date":"full",...e}),value:h,detail:{year:i,month:s,day:o,...d?{}:{hour:a,minute:u,second:c}}}}const r=/(?:(\d{2,4})[/-](\d{1,2})[/-](\d{1,2}))?\s*(?:(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?/u.exec(t.trim());if(r){const[,t,n,i,s,o,a]=r,u=t=>void 0===t?void 0:Number(t),c=t=>s&&o&&!a?0:t,f={year:(t=>t&&t<100?t+2e3:t)(u(t)),month:u(n),day:u(i),hour:u(s),minute:u(o),second:c(u(a))},d=void 0===t&&void 0===n&&void 0===i,h=void 0===s&&void 0===o&&void 0===a,l=M({...f,month:f.month-1}).toDate();return{display:D(l,{type:h?"date":d?"time":"full",...e}),value:d?void 0:l,detail:h?{year:f.year,month:f.month,day:f.day}:d?{hour:f.hour,minute:f.minute,second:f.second}:f}}}return null},Y=(t,e)=>{const n=_("number"==typeof t?new Date(t):t),r=_("number"==typeof e?new Date(e):e);return n&&n.value?r&&r.value?r.value.getTime()-n.value.getTime():-1:1},S=(t,e=!1)=>t?Array.isArray(t)?t.map((t=>"string"==typeof t?{name:t}:t)):"string"==typeof t?[{name:t}]:"object"==typeof t&&t.name?[t]:(console.error(`Expect 'author' to be \`AuthorInfo[] | AuthorInfo | string[] | string ${e?"":"| false"} | undefined\`, but got`,t),[]):[],w=t=>{if(t){if(Array.isArray(t))return t.map(s);if("string"==typeof t)return[s(t)];console.error("Expect 'category' to be `string[] | string | undefined`, but got",t)}return[]},O=t=>{if(t){if(Array.isArray(t))return t;if("string"==typeof t)return[t];console.error("Expect 'tag' to be `string[] | string | undefined`, but got",t)}return[]},b=t=>{if("string"!=typeof t||""===t)return!1;const e=/^(?:\w+:)?\/\/(\S+)$/u.exec(t);if(!e)return!1;const n=e[1];return!!n&&(/^localhost[:?\d]*(?:[^:?\d]\S*)?$/u.test(n)||/^[^\s.]+\.\S{2,}$/u.test(n))},L=t=>t.startsWith("/"),T=t({name:"IconBase",props:{name:{type:String,default:""},color:{type:String,default:"currentColor"}},setup:(t,{slots:n})=>()=>e("svg",{xmlns:"http://www.w3.org/2000/svg",class:["icon",`${t.name}-icon`],viewBox:"0 0 1024 1024",ariaLabelledby:t.name},[e("title",{id:t.name,lang:"en"},`${t.name} icon`),e("g",{fill:t.color},n.default?.())])}),x=t=>{const e=r();return n((()=>t[e.value]))},H=()=>n((()=>i().value.title)),z=new Map;let A;__VUEPRESS_SSR__||(document.addEventListener("mousedown",(t=>{A=t})),document.addEventListener("mouseup",(t=>{for(const e of z.values())for(const{documentHandler:n}of e)n(t,A)})));const C=(t,e)=>{let n=[];return Array.isArray(e.arg)?n=e.arg:e.arg instanceof HTMLElement&&n.push(e.arg),(r,i)=>{const s=e.instance.popperRef,o=r.target,a=i?.target,u=!e||!e.instance,c=!o||!a,f=t.contains(o)||t.contains(a),d=t===o,h=n.length&&n.some((t=>t?.contains(o)))||n.length&&n.includes(a),l=s&&(s.contains(o)||s.contains(a));u||c||f||d||h||l||e.value(r,i)}},E={beforeMount(t,e){z.has(t)||z.set(t,[]),z.get(t).push({documentHandler:C(t,e),bindingFn:e.value})},updated(t,e){z.has(t)||z.set(t,[]);const n=z.get(t),r=n.findIndex((t=>t.bindingFn===e.oldValue)),i={documentHandler:C(t,e),bindingFn:e.value};r>=0?n.splice(r,1,i):n.push(i)},unmounted(t){z.delete(t)}},U=/#.*$/u,N=t=>{const e=U.exec(t);return e?e[0]:""},I=t=>decodeURI(t).replace(U,"").replace(/(index)?\.(md|html)$/,""),k=(t,e)=>{if(void 0===e)return!1;const n=I(t.path),r=I(e),i=N(e);return i?i===t.hash&&(!r||n===r):n===r};class W{constructor(){const t="message-container",e=document.getElementById(t);e?this.containerElement=e:(this.containerElement=document.createElement("div"),this.containerElement.id=t,document.body.appendChild(this.containerElement))}pop(t,e=2e3){const n=document.createElement("div");n.className="message move-in",n.innerHTML=t,this.containerElement.appendChild(n),e>0&&setTimeout((()=>{this.close(n)}),e)}close(t){t.className=t.className.replace("move-in",""),t.className+="move-out",t.addEventListener("animationend",(()=>{t.remove()}))}}"production"===process.env.NODE_ENV||Object.freeze({}),"production"===process.env.NODE_ENV||Object.freeze([]);const F=(t,...e)=>{const n=t.resolve(...e),r=n.matched[n.matched.length-1];if(!r?.redirect)return n;const{redirect:i}=r,s="function"==typeof i?i(n):i;const o=(t=>"string"==typeof t)(s)?{path:s}:s;return F(t,{hash:n.hash,query:n.query,params:n.params,...o})};export{T as IconBase,W as Message,s as capitalize,E as clickOutSideDirective,Y as compareDate,S as getAuthor,w as getCategory,_ as getDate,N as getHash,O as getTag,L as isAbsoluteUrl,k as isActiveLink,b as isUrl,I as normalizePath,F as resolveRouteWithRedirect,o as strictCapitalize,D as timeTransformer,x as useLocaleConfig,H as usePageTitle};
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Module.<anonymous> (/home/user/vue2test/dist/.server/app.js:26:14)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
// dist/.server/app.js:29
var mrhopeVuepressClient = require("@mr-hope/vuepress-shared/lib/client");

And if my package contain "type": "module", it will be

Error [ERR_REQUIRE_ESM]: require() of ES Module ....
DerYeger commented 2 years ago

@Mister-Hope Great find!

I gave it a look with my project, and found that adding the offending packages to ssr.noExternal in the project's own vite.config.ts also fixed the issue.

import { defineConfig } from 'vite'

export default defineConfig({
  root: 'docs',
  optimizeDeps: {
    include: ['vue'],
  },
  // @ts-expect-error Invalid types can be ignored
  ssr: {
    noExternal: ['d3-drag', 'd3-force', 'd3-selection', 'd3-zoom'],
  },
})

So it seems no changes to Vuepress or the file mentioned above are required.

The only issue I'm facing with this solution, is that the types are not correct as the ssr property is supposedly missing in UserConfigExport.

Mister-Hope commented 2 years ago

@Mister-Hope Great find!

I gave it a look with my project, and found that adding the offending packages to ssr.noExternal in the project's own vite.config.ts also fixed the issue.

import { defineConfig } from 'vite'

export default defineConfig({
  root: 'docs',
  optimizeDeps: {
    include: ['vue'],
  },
  // @ts-expect-error Invalid types can be ignored
  ssr: {
    noExternal: ['d3-drag', 'd3-force', 'd3-selection', 'd3-zoom'],
  },
})

So it seems no changes to Vuepress or the file mentioned above are required.

The only issue I'm facing with this solution, is that the types are not correct as the ssr property is supposedly missing in UserConfigExport.

I am getting your point, but the solution you mentioned, did you check it in vitepress or vuepress? The expect behavior of vuepress, is that it should omit any vite.config,js files. If you add that file in one your vuepress folder and vuepress is reading it, it should be regarded as another bug.

Waiting for your reply. 🙂

DerYeger commented 2 years ago

@Mister-Hope Great find! I gave it a look with my project, and found that adding the offending packages to ssr.noExternal in the project's own vite.config.ts also fixed the issue.

import { defineConfig } from 'vite'

export default defineConfig({
  root: 'docs',
  optimizeDeps: {
    include: ['vue'],
  },
  // @ts-expect-error Invalid types can be ignored
  ssr: {
    noExternal: ['d3-drag', 'd3-force', 'd3-selection', 'd3-zoom'],
  },
})

So it seems no changes to Vuepress or the file mentioned above are required. The only issue I'm facing with this solution, is that the types are not correct as the ssr property is supposedly missing in UserConfigExport.

I am getting your point, but the solution you mentioned, did you check it in vitepress or vuepress? The expect behavior of vuepress, is that it should omit any vite.config,js files. If you add that file in one your vuepress folder and vuepress is reading it, it should be regarded as another bug.

Waiting for your reply. 🙂

Vuepress 2.

My Vuepress config includes

bundler: '@vuepress/vite',
  bundlerConfig: {
    viteOptions: {
      configFile: 'docs/vite.config.ts',
    },
  },

so it should be included.

Alternatively, the above mentioned config can be inlined in the bundlerConfig property. I just prefer a separate file.

Mister-Hope commented 2 years ago

This bug I believe, acually comes from an internal change in vite@2.7.

See the docs: https://vitejs.dev/guide/ssr.html#ssr-externals

image

Though it still says "In future", but it seems like the default behavoir already. That's why we have this bug.

Mister-Hope commented 2 years ago

Alternatively, the above mentioned config can be inlined in the bundlerConfig property. I just prefer a separate file.

Yeah, I just noticed that. I thought the file I referenced have highest property before you remind me. It's a plugin, but it will still be infected by users config. Thanks reminding that.

Mister-Hope commented 2 years ago

So, should it really be a bug under this reason? Ideas are welcome. If you guys agree it's not a bug and something we should deal with ourselves, we can close this issue.

DerYeger commented 2 years ago

So, should it really be a bug under this reason? Ideas are welcome. If you guys agree it's not a bug and something we should deal with ourselves, we can close this issue.

Considering the Vite change you referenced above, I'd argue it's not a bug with Vuepress/Vitepress but an issue with Vite caused by the ongoing ESM/CJS ecosystem migration.

The ssr.noExternal workaround works fine, until packages have migrated or Vite's detection heuristic improves.

Mister-Hope commented 2 years ago

Emm, just have a rethink of it. If all plugins are providing esm syntax on client side, all the plugins should be added into noExternal right? In that case maybe @vuepress/bundler-vite should do the job for plugins. And for the rest, users or developers should handle them.

meteorlxy commented 2 years ago

@Mister-Hope We've already add all official plugins to noExternal.

https://github.com/vuepress/vuepress-next/blob/73d297f321750de098c22c8c774dbe934475ddcb/packages/%40vuepress/bundler-vite/src/plugins/createMainPlugin.ts#L107-L109

I solved lots of issues when trying to support vite. I must have noticed the ssr.noExternal issue, but forgot to mention it in the docs... 😓

filonik commented 2 years ago

@Mister-Hope Great find!

I gave it a look with my project, and found that adding the offending packages to ssr.noExternal in the project's own vite.config.ts also fixed the issue.

import { defineConfig } from 'vite'

export default defineConfig({
  root: 'docs',
  optimizeDeps: {
    include: ['vue'],
  },
  // @ts-expect-error Invalid types can be ignored
  ssr: {
    noExternal: ['d3-drag', 'd3-force', 'd3-selection', 'd3-zoom'],
  },
})

So it seems no changes to Vuepress or the file mentioned above are required.

The only issue I'm facing with this solution, is that the types are not correct as the ssr property is supposedly missing in UserConfigExport.

The ssr.noExternal works great, however I was having problems with HMR during development until I removed optimizeDeps. Specifically, I was getting reference errors for clientAppEnhance0 or clientAppEnhances, resulting in having to manually refresh the page. Just thought I'd leave that here in case anybody else experiences this issue...

Correction: While the issue briefly went away upon making the configuration changes, it has since returned. Therefore, it is probably unrelated to optimizeDeps, and possibly unrelated to this issue entirely. For reference, this is the error that appears (inconsistently) when running in development mode and triggering HMR by making some changes:

Uncaught (in promise) ReferenceError: can't access lexical declaration 'clientAppEnhances' before initialization

This is in a project that uses clientAppEnhance.js. I'll keep looking into it. If the error persists, it probably warrants its own issue.

Mister-Hope commented 2 years ago

@Mister-Hope We've already add all official plugins to noExternal.

https://github.com/vuepress/vuepress-next/blob/73d297f321750de098c22c8c774dbe934475ddcb/packages/%40vuepress/bundler-vite/src/plugins/createMainPlugin.ts#L107-L109

I solved lots of issues when trying to support vite. I must have noticed the ssr.noExternal issue, but forgot to mention it in the docs... 😓

I think we may need to automatically add all the plugins into the list in @vuepress/bundler-vite, there is not need to let all the plugin authors add their plugins themselves.

Also, I am negative to hard coding all the official plugins here, they should only be added when they are imported into a vuepress project.

meteorlxy commented 2 years ago

This should have been fixed by our recent release.

superchangme commented 1 month ago

或者,可以将上述配置内联在 bundlerConfig 属性中。我只是更喜欢一个单独的文件。

是的,我刚刚注意到了。在你提醒我之前,我以为我引用的文件具有最高属性。这是一个插件,但它仍然会被用户的配置感染。谢谢提醒。

This bug I believe, acually comes from an internal change in vite@2.7.

See the docs: https://vitejs.dev/guide/ssr.html#ssr-externals

image

Though it still says "In future", but it seems like the default behavoir already. That's why we have this bug.

so how we fix it use vite below 2.7?