账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    webpack如何打包cdn引用的图片文件,本地文件引用正常,react项目
    58
    0
    {
              test: /\.(png|jpg)$/,
              loader: 'url-loader?limit=819&name=images/[hash:8].[name].[ext]'
            },
                {
                    test: /\.(htm|html)$/i,
                     use:[ 'html-withimg-loader'] 
                }
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 在Webpack中,为了打包CDN引用的图片文件并确保本地文件引用正常,可以使用以下步骤:

      1. 在webpack.config.js文件中添加依赖项:

      javascript module.exports = { ... // 在这里添加CDN的插件 module: { rules: [ // 避免使用绝对路径 { test: /\.(png|jpg|gif)$/, use: { loader: 'url-loader', options: { limit: 1024 * 1024, outputPath: 'images', }, }, }, ], }, };

      在上述配置中,我们使用了url-loader插件来处理CDN引用的图片文件。url-loader可以将URL转换为图片文件的base64编码,然后将编码后的文件路径添加到outputPath配置中。

      1. 在你的React组件中使用图片资源:

      ```javascript import React from 'react'; import { Image } from 'react-native';

      const MyComponent = () => { const [image, setImage] = useState(null);

      useEffect(() => { fetch('https://cdn.example.com/image.jpg') .then(response => response.arrayBuffer()) .then(data => { setImage(new Image().initWithURL(data)); }) .catch(error => { console.error(error); }); }, []);

      return ( ); };

      export default MyComponent; ```

      在上述代码中,我们首先使用fetch函数从CDN引用的图片文件中获取一个arrayBuffer,然后使用Image组件的initWithURL方法初始化一个Image对象,并将获取到的arrayBuffer设置为image的source属性。

      注意:你需要将https://cdn.example.com/image.jpg替换为你的CDN图片的实际URL。在实际应用中,你可以使用像axiosfetchlocation.href等方法来获取图片文件的URL。

      此外,由于React Native是纯JavaScript应用,所以需要在代码中导入Image组件,而不是直接在React中使用<Image>元素。在React Native中,你可以这样做:

      ```javascript import React from 'react'; import { Image } from 'react-native';

      const MyComponent = () => { const [image, setImage] = useState(null);

      useEffect(() => { fetch('https://cdn.example.com/image.jpg') .then(response => response.arrayBuffer()) .then(data => { setImage(new Image().initWithURL(data)); }) .catch(error => { console.error(error); }); }, []);

      return ( ); };

      export default MyComponent; ```

      在上述代码中,我们导入了Image组件,并在组件中初始化了一个Image对象,并将获取到的arrayBuffer设置为image的source属性。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部