react-scripts 变量未定义,但 webpack 工作正常
react-scripts variable is not defined, but webpack working fine
在react中,我在一个js文件中声明了一个const变量,附加到index.html
在我的反应文件 App.js 中,如果我使用变量:
- 运行 react-scripts start/build got 'myVariable' 未定义 no-undef
- 运行 webpack 和 html 工作正常
my example in codeSandbox(注意:codeSandbox 示例也可以正常工作)
index.html 在 public 文件夹中(已添加 config.js)
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="config.js"></script>
</body>
index.html在webpack生成的dest文件夹中
<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>
);
}
我想知道:
- 使用
react-scripts start/build
时是否可以通过编译错误?
- 使用webpack,如何检查这种未定义变量的问题?
附加问题:
- 如何使用 webpack/webpack-dev-server 检查未使用的变量?
例如使用react-scripts start
可以得到警告:'myVariable' is assigned a value but never used
感谢您的帮助!
你应该导出变量然后在里面导入它 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 规则,指定文件上的错误将被忽略。
在react中,我在一个js文件中声明了一个const变量,附加到index.html
在我的反应文件 App.js 中,如果我使用变量:
- 运行 react-scripts start/build got 'myVariable' 未定义 no-undef
- 运行 webpack 和 html 工作正常
my example in codeSandbox(注意:codeSandbox 示例也可以正常工作)
index.html 在 public 文件夹中(已添加 config.js)
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="config.js"></script>
</body>
index.html在webpack生成的dest文件夹中
<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>
);
}
我想知道:
- 使用
react-scripts start/build
时是否可以通过编译错误? - 使用webpack,如何检查这种未定义变量的问题?
附加问题:
- 如何使用 webpack/webpack-dev-server 检查未使用的变量?
例如使用react-scripts start
可以得到警告:'myVariable' is assigned a value but never used
感谢您的帮助!
你应该导出变量然后在里面导入它 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 规则,指定文件上的错误将被忽略。