【问题标题】:When you run, npm start, how is index.js picked up for running当你运行时,npm start,index.js 是如何被拾取运行的
【发布时间】:2020-05-15 10:00:05
【问题描述】:

我使用

创建了一个反应项目
create-react-app react-app

然后创建了一个包含所有文件夹的 react-app。 (使用 Visual Studio 代码)

然后使用 rimraf 删除“src”文件夹

然后打开 index.html 并删除其所有内容。

那么!并在 index.html 中输入并创建 HTML 样板代码

然后在里面创建了下面的div,

 <div id="root">
      React Component goes here....
 </div>

现在创建了“src”文件夹,并在其中创建了包含以下内容的“index.js”,

import React from "react";
import ReactDOM from "react-dom";
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import HelloComponent from "./components/helloComponent";
import BindingComponent from "./components/bindingComponent";

ReactDOM.render(
  <React.Fragment>
    <HelloComponent name={"Rohit"} />
    <HelloComponent />

    <BindingComponent></BindingComponent>
  </React.Fragment>,
  document.querySelector("#root")
);

在“package.json”中,我在脚本部分有以下内容,

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

还在 components 文件夹中创建了 React 组件

现在当我使用npm start 运行时,它如何调用 index.js ???

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    npm startnpm run start 的简写,它调用 react-scripts 启动脚本。

    如果我们调查他们github repo 中的脚本,我们会发现该条目是在他们的 webpack.config.js 文件中配置的:

    entry:
          isEnvDevelopment && !shouldUseReactRefresh
            ? [
                webpackDevClientEntry,
                paths.appIndexJs,
              ]
            : paths.appIndexJs,
    

    路径在paths.js文件中定义:

    module.exports = {
      dotenv: resolveApp('.env'),
      appPath: resolveApp('.'),
      appBuild: resolveApp('build'),
      appPublic: resolveApp('public'),
      appHtml: resolveApp('public/index.html'),
      appIndexJs: resolveModule(resolveApp, 'src/index'),
      appPackageJson: resolveApp('package.json'),
      appSrc: resolveApp('src'),
      appTsConfig: resolveApp('tsconfig.json'),
      appJsConfig: resolveApp('jsconfig.json'),
      yarnLockFile: resolveApp('yarn.lock'),
      testsSetup: resolveModule(resolveApp, 'src/setupTests'),
      proxySetup: resolveApp('src/setupProxy.js'),
      appNodeModules: resolveApp('node_modules'),
      publicUrlOrPath,
    };
    

    【讨论】:

    • 感谢@Alexandar 的回答。但是 path.js 中的 index.js 在哪里。它只有 src/index。对于 html,它被称为 public/index.html。另请注意,我在 src 文件夹中只有 index.js。我已删除所有其他应用程序文件。
    • 感谢@Alexandar 的回答。那么 path.js 中的这一行是否决定 index.js 将被调用? "appIndexJs: resolveModule(resolveApp, 'src/index')"
    • @RohitT,是的,文件扩展名在resolveModule函数中解析。
    【解决方案2】:

    react-scripts 将其添加到正文中。所以你需要添加它。

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 2021-07-31
      • 1970-01-01
      • 2019-03-05
      • 2021-01-25
      相关资源
      最近更新 更多