이창규
이창규

Reputation: 11

external url in webpack alias

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',
    }
  }
}

Upvotes: 1

Views: 2538

Answers (1)

therewillbecode
therewillbecode

Reputation: 7180

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} />

Upvotes: 1

Related Questions