简体   繁体   中英

Webpack resolve a directory for import paths (goCardless as a boiletplate)

Currently a typical component will look like the below code. Note that using the paths to the file has become problematic and ugly. Moving a file causes massive issues with updating paths across multiple components.

This truly takes away from the component based experience when a path change can break everything and cause mass find and replace of paths.

In an ideal world the displayName would be the import reference and searched for within the directory.

'use strict';

//libs
import React from 'react';

//components
import TopFeatures from '../../headphones/subcomponents/top-features';
import Prices from './prices';
import Image from '../../layout/image';
import InlineRatingElement from '../../reviews/rating';

//helpers
import { getImageUrl } from '../../helpers/app/image';
import { initiateInlineRatings } from '../../helpers/app/inline-ratings';

export default class HDOverview extends React.Component {
  displayName = 'HDOverview'

  static propTypes = {
    vendor: React.PropTypes.string.isRequired
  }

  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div>
        JSX
      </div>
   );
  }
}

I am looking to do something like this:

import TopFeatures from 'TopFeatures';//TopFeatures is the displayName
import Prices from 'Prices'; //Prices is the displayName etc.
import Image from 'Image';
import InlineRatingElement from 'InlineRatingElement';

//helpers
import { getImageUrl } from 'ImageHelper';
import { initiateInlineRatings } from 'InlineRatingHelper';

Webpack has a great tutorial on resolve aliases here: http://xabikos.com/javascript%20module%20bundler/javascript%20dependencies%20management/2015/10/03/webpack-aliases-and-relative-paths.html

However this insinuates that the path to the component would need to be logged in one place - in an ideal world there would be a way to dynamically check paths / directories to find the displayName that matches. Note that we have 200 components, so manually creating that list is do-able but sizable.

Having looked around I have seen people using

require("components!/layout/image")

however we would like to stick to the import technique and not go back to require.

Any suggestions or advice are greatly appreciated.

I think that this is, unfortunately, a limitation of node , npm .

There are workarounds to get absolute/mapped paths to work in npm but all of these have drawbacks: https://gist.github.com/branneman/8048520

Another option is individual npm packages for each component, but this adds a lot of overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM