【发布时间】:2019-03-15 16:24:39
【问题描述】:
我的情况如下:
我为 React 创建了一个组件库。所以我有一个包(与 Rollup 捆绑在一起),其中包含一些图片(目前只有一个用于组件的 GIF 图片)。
使用我的图片的组件是这样的:
import React from 'react';
import PropTypes from 'prop-types';
import ui_spinner from '../../../assets/ui_progress.gif';
/**
* CircularSpinner
* Add a spinner when the user needs to wait
*/
class CircularSpinner extends React.PureComponent {
static propTypes = {
/** Width of the component */
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** Height of the component */
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** Style of the component (overload existing properties) */
style: PropTypes.object,
}
static defaultProps = {
width: 128,
height: 128,
style: {},
}
render() {
const { style, width, height } = this.props;
return (
<img src={ui_spinner} width={width} height={height} style={style} alt="ui_progress" aria-busy="true" />
);
}
}
export default CircularSpinner;
当我构建它时,它没问题。
现在我使用 create-react-app 创建了一个 React 应用程序,并且我想测试我的组件库。为此,我使用npm link(为了避免推送我的 npm 包)。我的组件在我的测试应用程序中正常,但图片(我的 CircularSpinner 组件中的 GIF)没有显示。
所以我的问题是:如何在带有 Rollup 的 JS 包中包含一些资产?我的工作方法正确吗?
我的汇总配置如下:
import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import url from 'rollup-plugin-url'
const config = {
input: 'src/index.js',
external: ['react'],
output: {
format: 'umd',
name: 'react-components',
globals: {
react: "React"
}
},
plugins: [
babel({
exclude: "node_modules/**"
}),
uglify(),
url(),
]
}
export default config
我使用 rollup -c -o dist/index.js 构建。
dist 文件夹的内容如下:
dist/
assets
92be5c546b4adf43.gif
index.js
使用我的图片的组件在我的测试应用程序中是这样的:
<img src="92be5c546b4adf43.gif" width="128" height="128" alt="ui_progress" aria-busy="true">
感谢您的帮助!
达米安
【问题讨论】:
-
查看您的 devtools 网络选项卡 - 图像是否正在尝试加载?你有404吗?他们试图从什么路径加载?
-
我得到了 URL localhost:3000/92be5c546b4adf43.gif 的 200 状态。我感觉我的照片没有正确曝光。
-
我找到了解决方案(见我的下一个答案),谢谢您的回复!
标签: javascript reactjs npm bundle rollup