How to use Webpack to load a static file with a relative path with React?

875 views Asked by At

I'm trying to create a map component in React using the Tangram Library. I got it working with Webpack alone but it started bugging out when I used react in the mix.

I've tried using various loaders such as a raw loader, a yaml loader and so forth, but none of them have worked thus far.

The map component looks as follows:

// -- Import dependencies --
import React from 'react';
import { Map } from 'react-leaflet';

// -- Import Tangram --
import Tangram from 'tangram';
import yaml from 'js-yaml';
import data from '!!raw-loader!./scene.yaml';
export default class LeafletMap extends React.Component {
  componentDidMount() {
    const layer = Tangram.leafletLayer({
      scene: data
    });
    layer.addTo(this.map.leafletElement);
  }

  render() {
    return (
      <Map center={[40.70532, -74.00976]} zoom={15} ref={(ref) => {     this.map = ref }} />
    );
  }
}

How can I actually load the scene.yaml so that the Tangram library makes use of it ?

In the end it responds with a 404 as the file isn't found.

1

There are 1 answers

0
Toni On

The solution was, that the static files weren't being copied to the bundle built by webpack.

I solved it by using the CopyPlugin in the webpack config and copying the files to a folder respecting the relative path name, like so:

const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: './main.js',
  output: {
    filename: './bundle.js'
  },
  plugins: [
    new CopyPlugin([
      { from: 'src', to: 'src' },
    ]),
  ],
};