Best way to add asset path variable with React and JSX?

And*_*old 4 javascript assets jsx reactjs

What is the best way to add asset path variables?

I am working on an app that has a different asset dir depending on the environment (local, staging, production).

Right now, all my image paths are hard coded in the JSX which works totally fine when developing locally. However, when on staging, the asset path is slightly different.

这是我正在谈论的简单示例。

render() {
    return (
        <div className="home-container">
            <img className="home-container__logo" src="/images/ui/logos/imagename.png" />
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

imagesrc属性指向"/images". 这在其他环境中可能有所不同。

是否有添加资产路径 var 或执行类似操作的“反应方式” {% static 'images/ui/logos/imagename.png' %}

干杯

dye*_*yer 7

React 中没有用于资产路径的内置帮助程序,但您的直觉很好:这是一个很好的抽象,值得自己制作。如果您使用的是 webpack,您可以将模块解析设置为包含根 react 文件夹的路径,然后一个简单的解决方案可能如下所示:

# 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

如果您没有使用 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']
  }
}
Run Code Online (Sandbox Code Playgroud)