6
4

More than 3 years have passed since last update.

next.jsでabsoluteなpathをインポートしたい

Last updated at Posted at 2019-10-31

../../とかやらずにimportしたいなと思ったので、調べた。

こういうやつ

-import { InjectStoreContext, initializeData } from '../../../../../src/stores';
+import { InjectStoreContext, initializeData } from 'src/stores';

next.config.jsでwebpackに設定注入して、
eslintの設定も追記するとだいたいOK
雑にdiffも置いとく。

diff --git a/.eslintrc.js b/.eslintrc.js
index 5594d79..84bc5b3 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -8,13 +8,18 @@ module.exports = {
     ecmascript: 6,
     jsx: true,
   },
-  extends: ['airbnb', 'prettier', 'prettier/react'],
+  extends: ['airbnb', 'prettier', 'prettier/react', 'plugin:import/errors', 'plugin:import/warnings'],
   settings: {
     react: {
       createClass: 'createReactClass',
       version: 'detect',
     },
     'import/core-modules': ['styled-jsx/css'],
+    'import/resolver': {
+      'node': {
+        'paths': ['.']
+      },
+    },
   },
   parser: 'babel-eslint',
   plugins: ['react', 'react-hooks', 'prettier'],
diff --git a/next.config.js b/next.config.js
index bd98df1..d461392 100644
--- a/next.config.js
+++ b/next.config.js
@@ -1,4 +1,5 @@
 const webpack = require('webpack');
+const path = require('path');
 const withBundleAnalyzer = require('@next/bundle-analyzer')({
   enabled: process.env.ANALYZE === 'true',
 });
@@ -25,6 +26,13 @@ module.exports = withSass(
       withSourceMaps({
         webpack(config) {
           config.plugins.push(new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /ja/));
+          config.resolve.alias.src = path.join(__dirname, 'src');
           return config;
         },
         serverRuntimeConfig: {
diff --git a/pages/_app.js b/pages/_app.js
index a006c3f..4538e0e 100644
--- a/pages/_app.js
+++ b/pages/_app.js
@@ -3,13 +3,13 @@ import Router from 'next/router';
-import '../src/styles';
-import { InjectStoreContext, initializeData } from '../src/stores';
-import InjectThemeProvider from '../src/components/InjectThemeProvider';
+import 'src/styles';
+import { InjectStoreContext, initializeData } from 'src/stores';
+import InjectThemeProvider from 'src/components/InjectThemeProvider';
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4