Yêu cầu thg 2 21, 2022 3:59 SA 383 0 2
  • 383 0 2
0

NextJs: next.config.js use Redirects

Chia sẻ
  • 383 0 2

Chào anh chị, em có dùng Redirects của NextJs để chuyển hướng trang. File next.config.js của em hiện tại như thế này, nhưng Redirects không hoạt động, anh chị ai biết em sai ở đâu giúp em với ạ.

const withCSS = require('@zeit/next-css');
const withPlugins = require('next-compose-plugins');
const withOffline = require('next-offline');
const { GuessPlugin } = require('guess-webpack');
const withPWA = require('next-pwa');
require('dotenv').config();

const withEnv = {
  env: {
    DEPLOY_ENV: process.env.DEPLOY_ENV,
  },
};

module.exports = withPlugins([
  withCSS({
    webpack: function (config, { isServer }) {
      config.module.rules.push({
        test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
            name: '[name].[ext]',
          },
        },
      });
      return config;
    },
  }),
  withOffline({
    workboxOpts: {
      swDest: '../public/sw/service-worker.js',
    },
    async rewrites() {
      return [
        {
          source: '/service-worker.js',
          destination: '/_next/static/service-worker.js',
        },
      ];
    },
  }),
  withPWA({
    pwa: {
      disable: process.env.DEPLOY_ENV !== 'production' ? true : false,
      dest: 'public/sw',
      scope: '/sw',
    },
  }),
  withEnv,
  [
    {
      async redirects() {
        return [
          {
            source: '/product/:slug*',
            destination: '/:slug*',
            permanent: true,
          },
        ];
      },
    },
  ],
]);

2 CÂU TRẢ LỜI


Đã trả lời thg 3 4, 2022 2:20 SA
Đã được chấp nhận
0
const withRewrites = {
  async rewrites() {
    return [
      {
        source: '/product/:path*',
        destination: '/:path*',
      },
    ];
  },
};

module.exports = withPlugins([withRewrites]);
Chia sẻ
Đã trả lời thg 2 28, 2022 11:20 SA
0

nextConfig đặt sai chỗ, hiện tại nó nằm trong withPlugins như là 1 plugin, sửa lại như:

module.exports = withPlugins(
  [
   // Plugins
  ],
  {
    async redirects() {
      return [
        {
          source: '/product/:slug*',
          destination: '/:slug*',
          permanent: true,
        },
      ];
    },
  },
);

Ngoài ra khuyên bạn nên tách ra biến nextConfig và ngắn typing suggest tốt hơn như:

/**
 * @type {import('next').NextConfig}
 **/
const nextConfig = {
  poweredByHeader: false,
  // async redirect()
};

module.exports = withPlugins(
  [
   // Plugins
  ],
  nextConfig
);
Chia sẻ
thg 3 4, 2022 2:17 SA

Cảm ơn bạn đã support mình, lỗi này là do mình đang dùng nextjs ver cũ ạ, update lên 9.5.0 là được ạ

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí