【问题标题】:react-scripts variable is not defined, but webpack working finereact-scripts 变量未定义,但 webpack 工作正常
【发布时间】:2019-09-11 03:34:57
【问题描述】:

在反应中,我在 js 文件中声明了一个 const 变量,将其附加到 index.html
在我的反应文件 App.js 中,如果我使用变量:

  1. run react-scripts start/build got 'myVariable' is not defined no-undef
  2. 运行 webpack,html 工作正常

my example in codeSandbox(注意:codeSandbox 示例也可以正常工作)

公共文件夹中的index.html(添加了config.js)

 <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script src="config.js"></script>
  </body>

webpack生成的dest文件夹中的index.html

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script src="config.js"></script>
  <script type="text/javascript" src="main.js"></script>
</body>

config.js(声明变量服务器)

const server = 'my server';

App.js(直接在 react 脚本中使用变量)

function App() {
  return (
    <div className="App">
      this is server: {server}
    </div>
  );
}

我想知道:

  1. 使用react-scripts start/build时是否可以通过编译错误?
  2. 使用webpack,如何检查这种未定义变量的问题?

其他问题:

  1. 如何使用 webpack/webpack-dev-server 检查 no-unused-vars?
    例如使用react-scripts start 可以获得警告:'myVariable' is assigned a value but never used

感谢您的帮助!

【问题讨论】:

    标签: reactjs webpack webpack-dev-server react-scripts


    【解决方案1】:

    您应该导出变量然后将其导入App.js

    export const server = 'server';
    

    然后导入:

    import {server} from '../public/config.js'
    

    使用这种方法,将无需将config.js 脚本导入您的 Html 文件。

    我看到您的项目中有自己的webpack.config.js 文件,并且您还使用create-react-app 创建了项目。 create-react-app 使用名为 react-script 的包,其中包含自己的 webpack 配置文件。你可以在node-module\react-script\config 中看到 webpack 配置。 它将运行eslint,它负责您看到的警告。

    您可以通过将/* eslint-disable */ 添加到文件顶部来禁用App.js 上的eslint 规则,并且将忽略指定文件上的错误。

    【讨论】:

    • 感谢您的回复。对于另一个文件的导入导出变量,这不是我想在这里做的。由于导入导出将在编译时绑定值,但我正在做的是在运行时导入 config.js,所以我可以更改网络服务器上文件中的值以用于服务器配置。希望我能知道更好的解决方案。再次感谢。
    • 您也可以像/* global server otherVariable*/一样设置全局变量,并像/*eslint no-unused-vars: "error"*/一样设置未使用的变量规则,但是.eslintrc文件有更好的解决方案,请访问:rahulgaba.com/front-end/2019/02/17/…
    猜你喜欢
    • 2023-01-26
    • 2019-10-21
    • 2022-07-04
    • 1970-01-01
    • 2023-02-10
    • 2016-05-29
    • 2021-08-07
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多