Home   >   Using @ as an Alias for Component Paths in WordPress Block Development
March

When developing custom WordPress blocks using @wordpress/scripts, you can simplify your import paths by setting up @ as an alias for your src directory. This makes your code cleaner and easier to manage.

Step 1: Create a Webpack Configuration File

By default, @wordpress/scripts comes with a pre-configured Webpack setup. To extend it and add an alias, create a webpack.config.js file in the root of your project and add the following code:

const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const path = require('path');

module.exports = {
    ...defaultConfig,
    resolve: {
        ...defaultConfig.resolve,
        alias: {
            ...defaultConfig.resolve.alias,
            '@': path.resolve(__dirname, 'src'), // Set '@' to point to the 'src' directory
        },
    },
};
    

Step 2: Use the @ Alias in Your Imports

Once you’ve set up the alias, you can use @ instead of relative paths in your imports.

Before:

import { Tabs, TabsList, TabsTrigger } from "./ui/tabs";
    

After:

import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
    

Step 3: Update TypeScript Configuration (Optional)

If you’re using TypeScript, update your tsconfig.json file to recognize the @ alias. Add the following configuration:

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "@/*": ["src/*"]
        }
    }
}
    

Step 4: Restart Your Development Server

After making these changes, restart your development server to apply the new Webpack and TypeScript configurations.

Conclusion

By configuring Webpack to recognize @ as an alias, you can:

  • Avoid long relative import paths
  • Improve code readability and maintainability
  • Standardize import paths across your project

Now your project is set up with a cleaner, more efficient import structure. Happy coding!

Tags:

Categorised in: Wordpress