GithubHelp home page GithubHelp logo

gatsby-plugin-root-import's Introduction

gatsby-plugin-root-import

Set Webpack to resolve modules and aliases, allowing you to import modules from an absolute project path rather than relative ../../ paths.

Install

  1. Install the gatsby-plugin-root-import plugin:

    npm install --save-dev gatsby-plugin-root-import

    or

    yarn add --dev gatsby-plugin-root-import

Usage

Add into gatsby-config.js.

// gatsby-config.js

module.exports = {
  plugins: ["gatsby-plugin-root-import"],
};

Default Settings

If no options are specified, the plugin allows you access to the src folder and also it's contents automatically.

This means you should be able to import modules like such:

// importing gatsbyProject/src/someFolder/SomeComponent.js

import SomeComponent from "src/someFolder/SomeComponent";
// or more succinctly
import SomeComponent from "someFolder/SomeComponent";

Plugin Options

Plugin Options allows you to:

  1. Specify additional webpack resolve.modules search locations with the resolveModules key.
  2. All other option keys will become a Webpack alias.
// gatsby-config.js
const path = require("path");

module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-root-import",
      options: {
        resolveModules: [path.join(__dirname, "libs")],
        utils: path.join(__dirname, "src", "components", "utilities"),
      },
    },
  ],
};

This means you should be able to import modules like such:

// gatsbyProject/libs is now a searched resolve.modules directory
// importing gatsbybProject/libs/someLib/SomeLibComponent.js
import SomeLibComponent from "someLib/SomeLibComponent";

// from the 'utils' alias
// importing gatsbyProject/src/components/utilities/UtilityComponent.js
import UtilityComponent from "utils/UtilityComponent";

Jest testing

The new aliased paths lets Webpack correctly compile your app. However this does not mean that Jest, or other test runners will understand where those aliases point to.

When setting up testing with Jest, see moduleNameMapper to correctly map your your aliases to a path that Jest can understand.

For example:

// gatsby-config.js
const path = require("path");

module.exports = {
  // ...other configs
  plugins: [
    {
      resolve: "gatsby-plugin-root-import",
      options: {
        components: path.join(__dirname, "src", "web", "components"),
      },
    },
  ],
};

could work with a Jest map like:

// jest.config.js
module.exports = {
  // ...other configs
  moduleNameMapper: {
    "^components/(.*)": "<rootDir>/src/web/components/$1",
  },
};

Please see Jest's moduleNameMapper documentation for specific implementation details regarding format and options.

Deprecated Gatsby V1 Instructions

Install

  1. Install the gatsby-plugin-root-import plugin:

    npm install --save-dev --save-exact [email protected]

    or

    yarn add --dev [email protected]

Usage

Add into gatsby-config.js.

// gatsby-config.js

module.exports = {
  plugins: ["gatsby-plugin-root-import"],
};

Default Settings

If no options are specified, the plugin defaults to your project root folder.

This means you should be able to import modules like such:

// importing gatsbyProject/src/yourFolder/YourComponent.js

import YourComponent from "src/yourFolder/YourComponent";

Plugin Options

You can pass a root option. You can specify your own folder, such as src. This option corresponds with Webpack v3's resolve.root found here. This may be both a directory string, or an array of directory strings.

// gatsby-config.js
const path = require("path");

module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-root-import",
      options: {
        root: path.join(__dirname, "src"),
      },
    },
  ],
};

This means you can import modules with project's src folder as root:

// importing gatsbyProject/src/yourFolder/YourComponent.js

import YourComponent from "yourFolder/YourComponent";

gatsby-plugin-root-import's People

Contributors

dependabot[bot] avatar emarchak avatar hellobrian avatar mongkuen avatar tricoder42 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

gatsby-plugin-root-import's Issues

Eslint configuration

Hi there,

I am a gatsby beginner and added the plugin with following settings to my gatsby-config.js in order to allow root imports:

{
    resolve: 'gatsby-plugin-root-import',
    options: {
        src: path.join(__dirname, 'src'),
        components: path.join(__dirname, 'src/components'),
        graphql: path.join(__dirname, 'src/graphql'),
        images: path.join(__dirname, 'src/images'),
        layouts: path.join(__dirname, 'src/layouts'),
        pages: path.join(__dirname, 'src/pages'),
        services: path.join(__dirname, 'src/services'),
        utils: path.join(__dirname, 'src/utils'),
    },
}

The root import itself is working but I have errors regarding eslint. I am using vscode btw.
I tried adding alias settings to my .eslintrc like described here.
So I added the following settings to my .eslintrc

"settings": {
    "import/resolver": {
      "node": {
        "paths": ["src", "node_modules"]
      },
      "alias": {
        "map": [
          ["src", "./src"],
          ["components", "./src/components"],
          ["graphql", "./src/graphql"],
          ["images", "./src/images"],
          ["layouts", "./src/layouts"],
          ["pages", "./src/pages"],
          ["services", "./src/services"],
          ["utils", "./src/utils"]
       ]
      }
    }
  }

Also tried it without the "node" settings.
I am probably not the first trying to run gatsby root imports with eslint and vscode. Is it possible for someone who is running a similar setup to share his experience and/or settings?

Best regards

How to use ~ instead of ~/ in import module statement

// gatsby-config.js
const path = require('path')

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        "~": path.join(__dirname, 'src/')
      }
    }
  ]
}

This means you should be able to import modules like such:

// To import gatsbyProject/src/yourFolder/YourComponent.js

import YourComponent from '~/yourFolder/YourComponent' // working example
import YourComponent from '~yourFolder/YourComponent'  // wanted but not work

Peer dependency not fulfilled by gatsby 3

Using npm 7.20.5:

╰─ npm audit fix                                                                                                  

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   gatsby@"^3.1.2" from the root project
npm ERR!   peer gatsby@">=2.0.0" from [email protected]
npm ERR!   node_modules/gatsby-awesome-pagination
npm ERR!     gatsby-awesome-pagination@"^0.3.8" from the root project
npm ERR!   18 more (gatsby-plugin-feed, gatsby-plugin-image, ...)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer gatsby@">=1" from [email protected]
npm ERR! node_modules/gatsby-plugin-root-import
npm ERR!   gatsby-plugin-root-import@"^2.0.6" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   peer gatsby@">=1" from [email protected]
npm ERR!   node_modules/gatsby-plugin-root-import
npm ERR!     gatsby-plugin-root-import@"^2.0.6" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I'm not to sure why that definition is not correct.

Plugin breaks in Gatsby v3 when trying to use redux-toolkit

Issue: When using the plugin in conjunction with redux-toolkit and gatsby v3 I get the following error:

ERROR #98124  WEBPACK

Generating development JavaScript bundle failed

Can't resolve 'redux' in '[file path]\gatsby-starter-hello-world\node_modules\react-redux\es\connect'

If you're trying to use a package make sure that 'redux' is installed. If you're    
trying to use a local file make sure that the path is correct.

File: node_modules\react-redux\es\connect\mapDispatchToProps.js:1:0

failed Building development bundle - 11.424s
ERROR in ./node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js 3:0-79
Module not found: Error: Can't resolve 'redux' in '[file-path]\gatsby-starter-hello-world\node_modules\@reduxjs\toolkit\dist'
 @ ./src/redux/store.ts 4:0-50 6:15-29
 @ ./src/pages/index.tsx 7:0-32 11:11-16
 @ ./.cache/_this_is_virtual_fs_path_/$virtual/async-requires.js 16:11-18:5
 @ ./.cache/app.js 17:0-52 28:0-70 30:27-40 28:0-70

ERROR in ./node_modules/react-redux/es/connect/mapDispatchToProps.js 1:0-43
Module not found: Error: Can't resolve 'redux' in '[file-path]\gatsby-starter-hello-world\node_modules\react-redux\es\connect'
 @ ./node_modules/react-redux/es/connect/connect.js 5:0-70 50:71-105
 @ ./node_modules/react-redux/es/index.js 4:0-40 12:0-179
 @ ./src/pages/index.tsx 6:0-39 10:42-50
 @ ./.cache/_this_is_virtual_fs_path_/$virtual/async-requires.js 16:11-18:5
 @ ./.cache/app.js 17:0-52 28:0-70 30:27-40 28:0-70

webpack compiled with 2 errors

For some extra context, my current config has worked with the plugin in a Gatsby v2 environment.

Can't specify `src` as root directory

If I manually specify paths like this, absolute imports work:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        components: path.join(__dirname, 'src/components'),
        utilities: path.join(__dirname, 'src/utilities'),
      },
    },
  ],
];

But using root doesn't work:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        root: path.join(__dirname, 'src'),
      },
    },
  ],
];

Nor does specifying the plugin without options:

module.exports = {
  plugins: [
    'gatsby-plugin-root-import',
  ],
];

Environment

Versions

gatsby: 2.16.4
gatsby-plugin-root-import: 2.0.5

Other than this it works great. Thanks in advance 👍

Doesn't seem to be working with Gatsby v2??

I cannot seem to get this to work with Gatsby v2:
gatsby version = 2.0.0-beta.16
node version = v6.14.2
npm version = 3.10.10
gatsby-plugin-root-import = ^1.0.0

gatsby-config.js

var config = require("./config")

module.exports = {
  siteMetadata: {
    title: config.siteName,
  },
  plugins: [
     /* other plugins */
      'gatsby-plugin-root-import'
  ]
}

myComponent.js

import React from 'react'
import config from '~/config'

const myComponent= () => (   
     /* my component code, uses config.api.url */
)

export default myComponent

When I do a gatsby develop

ERROR  Failed to compile with 1 errors                                                                                                                    
This dependency was not found:

* ~/config in ./src/components/common/myComponent.js

To install it, you can run: npm install --save ~/config
✖ 「wdm」:
ERROR in ./src/components/common/myComponent.js
Module not found: Error: Can't resolve '~/config' in '/src/components/common'

Resolve path to unit test

When running my app, everything is running fine as expected. However, if I run a test using jest, the test can't make the connection of the path in my gatsby config file. Below is a hiearchy of what I am running into.

gatsby-config:

...

{
      resolve: "gatsby-plugin-root-import",
      options: {
        reducers: path.join(__dirname, "src/reducers"),
        sagas: path.join(__dirname, "src/sagas"),
        web: path.join(__dirname, "src/web"),
        test: path.join(__dirname, "src/web"), <-------- test cases don't live on the root
      },
    },

....

Screen Shot 2020-08-13 at 10 46 17 AM

Test Error:

● Test suite failed to run

    Cannot find module 'web/components/graphs/line-graph' from 'src/web/components/card/index.js'

    Require stack:
      src/web/components/card/index.js
      src/web/components/card/test/index.test.js

      1 | import React from "react"
      2 | import { string, array } from "prop-types"
    > 3 | import LineGraph from "web/components/graphs/line-graph"

Can't Resolve NPM Package

I have been using this plugin for a while and it works great.

Today, I wanted to see if I could use it for an npm package that I installed. As such, I added the following to the options object:

FontAwesome: path.join(__dirname, '@fortawesome/react-fontawesome'),

However, it does not seem to work.

Is it possible to create an alias for an npm package? If so, how?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.