1

My team moved all the images of company website into a CDN. (https://cdn.irobo.co.kr/images) However, I'd like to use those images without changing current code base, which has a lot of: (reactjs code)

<image src={require('img/common/logo.jpg')} />

here's the webpack config for the website:

{
  module: {
    loaders:[{
      test: /\.(png|jpg)$/,
      loader: 'file-loader?name=[name].[ext]',
    }],
  }
  ...
  resolve: {
    alias: {
      img: path.join(srcPath, 'app/img'),
    }
  }
}

Here's what I tried:

...
  resolve: {
    alias: {
      img: 'https://cdn.irobo.co.kr/images',
    }
  }
}
1
  • Webpack compiles the code. While compiling it transforms images, what you want to use is link to images. And download when ui loads. It can be achieved by <img src={cdn.irobo.co.kr/images/${path}}/> Wild idea : you can write a img loader, that just replaces the image urls. Commented Feb 7, 2017 at 7:31

1 Answer 1

1

Bundling assets from external urls with Webpack

The url-loader plugin for webpack gives you the ability to take use assets from external url by encoding them in base64.

The url loader works like the file loader, but can return a Data Url if the file is smaller than a byte limit.

The limit can be specified with a query parameter. (Defaults to no limit)

Remember to install the url-loader plugin as a project dependency.

npm install --save-dev url-loader

Configure the url-loader plugin

Here is a sample webpack config to set up the url-loader plugin.

webpack.config.js

module.exports = {
  entry: './main.js',
  output: {
    path: './build', // This is where the images and js will go
    publicPath: 'http://mycdn.com/', // used to generate URLs to e.g. images
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      // use ! to chain loaders
      { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      // inline base64 URLs for <=8k images, direct URLs for the rest
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }
};

Import the assets in your app

app.jsx

import image from '../build/image.jpg';

<img src={image} />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.