最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace hrefsrc value in JSX from relative path to full path? - Stack Overflow

programmeradmin6浏览0评论

project:

├── img
│   └── header.jpg
├── index.html
├── js
│   └── react.js
└── jsx
    └── header.jsx

header.jsx

var Header = React.createClass({
    render: function() {
        return (
            <img className="header" src="./img/header.jpg" alt="header"/>
        );
    }
});

When i deploy static files(js,css,image) to CDN host,the header.png full path will be http:// cdn/img/header.jpg;

But my project host is http:// example, the header.jpg can't be load, so i want to find a way to replace the src value(example:./img/header.jpg -->http:// cdn/img/header.jpg )

-----By the way------

Hope using gulp to solve this problem; I fond gulp-assetpaths is good way to replace in HTML, but not work in jsx

project:

├── img
│   └── header.jpg
├── index.html
├── js
│   └── react.js
└── jsx
    └── header.jsx

header.jsx

var Header = React.createClass({
    render: function() {
        return (
            <img className="header" src="./img/header.jpg" alt="header"/>
        );
    }
});

When i deploy static files(js,css,image) to CDN host,the header.png full path will be http:// cdn./img/header.jpg;

But my project host is http:// example., the header.jpg can't be load, so i want to find a way to replace the src value(example:./img/header.jpg -->http:// cdn./img/header.jpg )

-----By the way------

Hope using gulp to solve this problem; I fond gulp-assetpaths is good way to replace in HTML, but not work in jsx

Share Improve this question asked May 26, 2015 at 8:52 RavenRaven 2071 gold badge5 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

I would remend you to look at Webpack which handles this really well. What you do is something like this:

var path = require('./img/header.jpg');
return <img className="header" src={path} alt="header" />

When you require the image, you get back the url to wherever that image is placed after the build has pleted. There are Webpack loaders that already handles this (like file-loader), but you can always create your own loader which rewrites the path to your CDN. Note that Webpack treats a require in Javascript the same was as it treats url in CSS, so it doesn't matter where you reference the image, it'll still be passed through your loader.

You can of course use different strategies for production and development, so you'd only return the CDN url for a production build.

发布评论

评论列表(0)

  1. 暂无评论