当前位置:网站首页>Circular reference of ES6 module
Circular reference of ES6 module
2022-07-06 08:11:00 【Drunk and carefree Neo】
The cause is an error message during development :Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
.
Because the error information is not clear , There is no clear explanation of the reasons and solutions on the Internet , So it took me a long time to find the reason . How to check , Even the most stupid is also the most effective “ Code deletion method ”, That is, delete the code line by line from the entry file , Until you locate the specific error location , Then judge the cause of the problem with your own knowledge and experience .
The reason is that import The circular reference of results in webpack Unable to parse correctly .
One 、 Introduction to circular reference
The simplest a Refer to the b,b Also cited a, This produces a circular reference .
What is more complicated is that the link is longer , for example a -> b -> c -> d -> a.
Circular references may cause memory stack overflow . But there is not necessarily a problem , such as b Two methods are derived ,a The reference is b Method of export fn1, and b It's in the way fn2 Quoted in a, In fact, there will be no problem in this situation .
But due to possible risks , And it's hard to find , So try to avoid using circular references when writing code .
Two 、 Check in the project
utilize webpack Plug in for circular-dependency-plugin It is very convenient to check the circular reference problem in the project .
( Not all circular references have problems , Therefore, this plug-in is recommended to be used when troubleshooting problems , Whether to open it during development depends on personal needs .)
- Installing a plug-in :
npm i circular-dependency-plugin -D
- stay webpack Add in configuration file plugins To configure .
const CircularDependencyPlugin = require('circular-dependency-plugin')
export default {
...,
plugins: [
...,
new CircularDependencyPlugin(
{
exclude: /node_modules/,
include: /src/,
failOnError: false,
allowAsyncCycles: false,
cwd: process.cwd(),
}
),
]
}
- Restart project , You can see the warning message of circular reference in the startup command line , The plug-in will help you locate the file path of the problem .
3、 ... and 、esm Reference handling for
ESM(es modules, namely es6 modularization ) It is loaded at compile time , and commonJs The runtime load of is different .esm Be as static as possible , The dependencies of the modules can be determined at compile time , Because of this ,esm It can be carried out through static analysis tree shaking Optimize .
Code example :
- main.js
import a from './a'
console.log(a)
- a.js
console.log(' perform a')
import b from './b'
console.log(b)
console.log(' Import b after ')
export default ' I am a a modular '
- b.js
console.log(' perform b')
import a from './a'
console.log(a)
console.log(' Import a after ')
export default ' I am a b modular '
- perform main.js, Output results :
// main.js in import 了 a, Advanced to a analysis
// import Statement parsing in advance ,a in import 了 b, So pause a Parsing , Enter b analysis
// b in import 了 a, but a At this time, the execution is not finished , To get the a The value is undefined, Then continue to parse b
b.js:1 perform b
b.js:3 undefined
b.js:4 Import a after
// b Finished parsing and got it b Export results of , Start back to a Continue to analyze
a.js:1 perform a
a.js:3 I am a b modular
a.js:4 Import b after
// a After analysis , go back to main.js Parsing performed
main.js:2 I am a a modular
esm Of import The command is executed at the compilation stage , Take precedence over its own content .
esm Don't care if there is a circular reference , Just generate a reference to the loaded module , When the code is not executed , The value of this reference is undefined.
Four 、webpack Reference handling for
Even if esm There is no exception in the circular reference , stay webpack Errors may also be reported during compilation , After all webpack Will be able to esm Downgrade to es5, There may be some differences in the degradation processing .
The same example code above ,webpack(v5.64.4) Execute after processing console.log(a)
An exception or error will appear when the statement :Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
.
- esm The way to deal with it is , First static analysis import, Then the dynamic export export ( Export reference ).
- webapck The way to deal with it is , First of all, put all the export Mentioned the beginning of the module , then import promote .
5、 ... and 、 resolvent
1、 Reference extraction
It is to extract the place with circular reference into another separate file , In other words, do not use circular references .
2、 The export function
Change the default export object to the form of export function , Get and export the result from the return value of the function .
Because each function will form a separate local scope , Different scopes have different data reference addresses .
In this way, the result of each introduction is a new reference , No conflict , This situation webpack It can also be handled normally .
Reference link :
https://blog.csdn.net/wu_xianqiang/article/details/100705034
https://zhuanlan.zhihu.com/p/141863544?from_voters_page=true
https://zhuanlan.zhihu.com/p/33049803
边栏推荐
- [research materials] 2022 enterprise wechat Ecosystem Research Report - Download attached
- 远程存储访问授权
- Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation
- Asia Pacific Financial Media | female pattern ladyvision: forced the hotel to upgrade security. The drunk woman died in the guest room, and the hotel was sentenced not to pay compensation | APEC secur
- Nc204382 medium sequence
- Binary tree creation & traversal
- 从 SQL 文件迁移数据到 TiDB
- Secure captcha (unsafe verification code) of DVWA range
- Data governance: Data Governance under microservice architecture
- Huawei cloud OBS file upload and download tool class
猜你喜欢
Asia Pacific Financial Media | designer universe | Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers
"Designer universe" APEC design +: the list of winners of the Paris Design Award in France was recently announced. The winners of "Changsha world center Damei mansion" were awarded by the national eco
IP lab, the first weekly recheck
Artcube information of "designer universe": Guangzhou implements the community designer system to achieve "great improvement" of urban quality | national economic and Information Center
Codeforces Global Round 19(A~D)
Hcip day 16
[redis] Introduction to NoSQL database and redis
Data governance: 3 characteristics, 4 transcendence and 3 28 principles of master data
07- [istio] istio destinationrule (purpose rule)
指针和数组笔试题解析
随机推荐
What is the use of entering the critical point? How to realize STM32 single chip microcomputer?
图像融合--挑战、机遇与对策
"Designer universe": "benefit dimension" APEC public welfare + 2022 the latest slogan and the new platform will be launched soon | Asia Pacific Financial Media
MFC sends left click, double click, and right click messages to list controls
[research materials] 2021 live broadcast annual data report of e-commerce - Download attached
Nft智能合约发行,盲盒,公开发售技术实战--合约篇
National economic information center "APEC industry +": economic data released at the night of the Spring Festival | observation of stable strategy industry fund
esRally国内安装使用避坑指南-全网最新
"Friendship and righteousness" of the center for national economy and information technology: China's friendship wine - the "unparalleled loyalty and righteousness" of the solidarity group released th
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Inspiration from the recruitment of bioinformatics analysts in the Department of laboratory medicine, Zhujiang Hospital, Southern Medical University
onie支持pice硬盘
Entity class design for calculating age based on birthday
Machine learning - decision tree
CAD ARX 获取当前的视口设置
C language - bit segment
【T31ZL智能视频应用处理器资料】
Interview Reply of Zhuhai Jinshan
Data governance: 3 characteristics, 4 transcendence and 3 28 principles of master data
[research materials] 2021 China online high growth white paper - Download attached