Permanent Tourist

The personal website of Mark Howells-Mead

When writing code in a React environment and building the scripts using a Webpack process, it sometimes makes sense to put shared components into a single folder, then link to them from the individual main files.

For example, when developing WordPress projects, I have a shared components folder which contains post selectors, an intelligent component which outputs a figure and img tag combination, and so on.

Hot-linking these shared components can be tricky if there is more than one build tree. For example, I have an “assets” watch process which compiles CSS and frontend JavaScript, and another which uses the WordPress Dependency Extraction Webpack Plugin to allow me to automatically pull in dependencies for scripts which are loaded in the editor. Each process has different watcher rules and output locations, and their folder structure is different.

So that I don’t have to manually define unwieldy relative paths (../../../../../_components, as an example), I got some help from Nico and added a custom rule to the build process. I define a constant in a config object in the main gulpfile.babel.js file: a relative path to the components folder, taking the location of the gulp file as a base.

const rootFolder = process.cwd();
const scriptsComponentsDir = `${rootFolder}/.build/assets/scripts/_components`,

I then pass this constant into the Gulp Webpack process as an alias resolve. (Reference here.) Thanks to the following code, I can now use @sharedcomponents in my scripts and the Webpack build process knows where to look.

resolve: {
	alias: {
		'@sharedcomponents': path.resolve(__dirname, scriptsComponentsDir),
	},
},

Here’s an example of using that value in a script file, which will be compiled by the build process.

import { PostSelector } from '@sharedcomponents/post-selector');

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google’s reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

This site uses Akismet to reduce spam. Learn how your comment data is processed.