簡體   English   中英

根文件中的console.log() 上面的導入語句在導入之前不會執行

[英]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 將捆綁每個模塊,包括AppAuth所需的模塊,然后調用console.log 當您訪問Auth.js時,所有模塊都已捆綁,因此唯一要做的就是調用console.log

詳細解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM