Open anyesu opened 1 year ago
Start a new pull request in StackBlitz Codeflow.
This is hard to fix. We're only rewriting to const initAMapApiLoader = __vite__cjsImport0_vueAmap["initAMapApiLoader"]
because vue-amap
does not export ESM, so we have to access the APIs through the default import after prebundling. Rewriting it for each referenced variables in code instead would be expensive, but not impossible since we're already doing it for SSR.
Waiting for you to have a better solution to fix this. I'm currently using this workaround since this case is used less in my projects.
import * as VueAMap from 'vue-amap';
VueAMap.initAMapApiLoader();
console.log(VueAMap.lazyAMapApiLoaderInstance);
Describe the bug
I used the vue-amap library in my project. I found that when I imported it using
import { lazyAMapApiLoaderInstance } from 'vue-amap'
, the value oflazyAMapApiLoaderInstance
was alwaysnull
instead of the latest value.The source code of
lazyAMapApiLoaderInstance
uses theexport let
syntax to delay initialization:ref: https://stackoverflow.com/a/32558929
Reproduction
https://stackblitz.com/edit/vitejs-vite-tdtcgx?file=src%2Fmain.js
Steps to reproduce
Use Vite and Vue CLI to start the project respectively. You can see from the log that the result in Vite is
null
, while the result in Vue CLI is the expectedobject
.Then build and run in production mode :
You can see that the behavior in production mode is the same as running in Vue CLI .
The source code after Vite transform is as follows:
However, the source code after Webpack transform is as follows:
The difference is that Webpack will convert
lazyAMapApiLoaderInstance
tovue_amap__WEBPACK_IMPORTED_MODULE_0__["lazyAMapApiLoaderInstance"]
, while Vite simply defines a local variable to take the value, soconsole.log
cannot read the latest value.So I think the behavior of Vite should be consistent with Webpack, at least the development mode and production mode should be consistent in Vite.
There are two ways to solve this problem:
Rename variable bindings like Webpack .
If simply use RegExp to replace them, it may affect other comments, strings, and local variables with the same name.
If AST is introduced for parsing, things may become much more complicated. I'm not familiar with AST either.
This should be documented, in this case the namespace import should be used instead of the named import as shown below. Also throwing warning in transformCjsImport .
https://github.com/vitejs/vite/blob/c7969597caba80cf5d3348cba9f18ad9d14e9295/packages/vite/src/node/plugins/importAnalysis.ts#L1002
System Info
Used Package Manager
pnpm
Logs
No response
Validations