使用 React 和 JSX 添加资产路径变量的最佳方式?
Best way to add asset path variable with React and JSX?
添加资产路径变量的最佳方式是什么?
我正在开发一个应用程序,该应用程序根据环境(本地、暂存、生产)具有不同的资产目录。
现在,我所有的图像路径都硬编码在 JSX 中,这在本地开发时工作得很好。但是,在暂存时,资产路径略有不同。
这是我所说的简单示例。
render() {
return (
<div className="home-container">
<img className="home-container__logo" src="/images/ui/logos/imagename.png" />
</div>
);
}
图像 src
属性指向 "/images"
。这在其他环境中可能有所不同。
是否有 "React way" 添加资产路径 var 或执行类似 {% static 'images/ui/logos/imagename.png' %}
的等效操作?
干杯
React 中没有内置的资产路径助手,但您的直觉很好:这是一个很好的抽象,值得您自己创建。如果您使用的是 webpack,则可以设置 module resolve 以包含根反应文件夹的路径,然后一个简单的解决方案可能如下所示:
# app/helpers/AssetHelper.js
export default {
imagePath: (path) => {
return `/images/${path}`
}
}
# your component
import { imagePath } from 'app/helpers/AssetHelper'
render() {
return (
<div className="home-container">
<img className="home-container__logo" src=${imagePath('ui/logos/imagename.png')} />
</div>
);
}
如果您不使用 Webpack 或某些等效项,路径将需要是相对的,这不是一个简单的解决方案。如果您使用的是 webpack,请查看 module resolve。它将允许您简化导入的文件路径。
使用模块解析的 webpack 配置示例:
# webpack.config.js
var path = require('path')
module.exports = {
entry: ...,
output: ...,
resolve: {
// specify your new path relative to the webpack config file
modules: [path.resolve(__dirname, './app'), 'node_modules']
}
}
添加资产路径变量的最佳方式是什么?
我正在开发一个应用程序,该应用程序根据环境(本地、暂存、生产)具有不同的资产目录。
现在,我所有的图像路径都硬编码在 JSX 中,这在本地开发时工作得很好。但是,在暂存时,资产路径略有不同。
这是我所说的简单示例。
render() {
return (
<div className="home-container">
<img className="home-container__logo" src="/images/ui/logos/imagename.png" />
</div>
);
}
图像 src
属性指向 "/images"
。这在其他环境中可能有所不同。
是否有 "React way" 添加资产路径 var 或执行类似 {% static 'images/ui/logos/imagename.png' %}
的等效操作?
干杯
React 中没有内置的资产路径助手,但您的直觉很好:这是一个很好的抽象,值得您自己创建。如果您使用的是 webpack,则可以设置 module resolve 以包含根反应文件夹的路径,然后一个简单的解决方案可能如下所示:
# app/helpers/AssetHelper.js
export default {
imagePath: (path) => {
return `/images/${path}`
}
}
# your component
import { imagePath } from 'app/helpers/AssetHelper'
render() {
return (
<div className="home-container">
<img className="home-container__logo" src=${imagePath('ui/logos/imagename.png')} />
</div>
);
}
如果您不使用 Webpack 或某些等效项,路径将需要是相对的,这不是一个简单的解决方案。如果您使用的是 webpack,请查看 module resolve。它将允许您简化导入的文件路径。
使用模块解析的 webpack 配置示例:
# webpack.config.js
var path = require('path')
module.exports = {
entry: ...,
output: ...,
resolve: {
// specify your new path relative to the webpack config file
modules: [path.resolve(__dirname, './app'), 'node_modules']
}
}