![](/img/trans.png)
[英]Why does JS alert execute before console.log when a loop is following the statements
[英]console.log() above import statements in root file does not execute before import
考慮一個 React 應用程序中的根 index.js 文件,它執行以下操作:
console.log("INDEX.JS")
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
//Internal Dependencies
import Auth from './containers/Auth';
import store from './store/store';
import ErrorBoundary from './containers/ErrorBoundary';
//Highcharts config
import highchartsConfig from './globalChartConfig';
//Global styles
import './index.css';
highchartsConfig();
render(
<Router>
<Provider store={store}>
<ErrorBoundary>
<Auth />
</ErrorBoundary>
</Provider>
</Router>,
document.getElementById('root')
);
導入語句在此文件頂部的console.log
語句之前執行。 將首先執行Auth.js
文件頂部的 console.log。 這是為什么?
以下console.log()
是第一個記錄到控制台的內容。
// Auth.js
console.log('AUTH')
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
您必須將 scope 的所有import
語句放在頂部。 此限制允許webpack
(不僅是 webpack,實際上是任何模塊加載器)靜態分析模塊導入了哪些模塊並在執行其主體之前加載它們。
console.log('first import then log')
import { foo } from 'foo'
將代碼放在import
之上會引發eslint
警告(import/first)
為什么
index.js
內部的console.log
會在導入之后觸發,而auth.js
內部會按預期的順序執行?
當調用index.js
(將呈現整個應用程序的入口點)時,webpack 將捆綁每個模塊,包括App
和Auth
所需的模塊,然后調用console.log
。 當您訪問Auth.js
時,所有模塊都已捆綁,因此唯一要做的就是調用console.log
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.