What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error:

./components/Hero.tsx:2:0
Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v'
  1 | import React, { useState } from 'react';
> 2 | import Video from '../media/HeroVideo1-Red-Compressed.m4v';
  3 | import { Button } from './SharedStyles';
  4 | import styled from 'styled-components'
  5 | import { MdKeyboardArrowRight, MdArrowForward } from 'react-icons/md';

Import trace for requested module:
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found

Thetsconfig.json file includes the following configurations:

  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]

To address this issue, I followed the top answer (by score) on this question, where I added index.d.ts to ./media with the declaration declare module '*.m4v'. Although this resolved the squiggly lines in Hero.tsx, it led to the error mentioned above on the client side.

I also tried the solutions provided in this question, but they did not yield the desired outcome. I am exploring alternatives to placing the video in the public folder. Any suggestions would be greatly appreciated.

Answer №1

After tirelessly experimenting with different approaches found in numerous stackoverflow threads, I eventually stumbled upon a solution that actually worked here. I made the following adjustments to nextConfig within next.config.js:

webpack(config, { isServer }) {
    const prefix = config.assetPrefix ?? config.basePath ?? '';
    config.module.rules.push({
      test: /\.mp4$/,
      use: [{
        loader: 'file-loader',
        options: {
          publicPath: `${prefix}/_next/static/media/`,
          outputPath: `${isServer ? '../' : ''}static/media/`,
          name: '[name].[hash].[ext]',
        },
      }],
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for managing blur events to execute personalized logic within Formik

I am currently delving into the world of React/Next.js, Formik, and Yup. My goal is to make an API call to the database upon blurring out of an input field. This call will fetch some data, perform database-level validation, and populate the next input fiel ...

React-query v5 - Updating or fetching outdated query

I am currently using the Tanstack/react-query v5.12.2 library and I am facing an issue with invalidating or refetching an inactive query using the useQueryClient() function. It seems that something has changed in version 5 of the library. I have tried sett ...

The reasons behind cancellations in API requests

Within the parent component, the open and setOpen states were passed down to the child component. The fetchData function included open as a dependency in the useEffect hook. In the child component, open was also added as a dependency for another fetchDat ...

When a nested component uses useEffect, will the page render on the server side or the client side?

I am currently developing a Next.js application and I have a query regarding rendering a page. The page contains a nested component where I have used useEffect, but the page does not receive any data from the server as it is the landing page. I would like ...

The error message "GetStaticPaths Error: Objects are not valid as a React child" indicates that an object was found when expecting a different type of data in a React component. To render a collection

I've encountered an issue while mapping the response from my get staticpath. Despite trying to destructure the response object, I haven't been successful. Consequently, when I select a single item, an error message is displayed. Feel free to chec ...

Mastering the art of duplicating an array of objects in TypeScript

I attempted the following strategy: this.strategies = []; this.strategiesCopy = [...this.strategies]; Unfortunately, it appears this method is not effective as it results in duplicates. ...

What is the process for initializing the default/prefilled value of an input element within a mat-form-field when the page loads?

I'm looking to create an HTML element where the default data (stored in the variable 'preselectedValue') is automatically filled into the input field when the component loads. The user should then be able to directly edit this search string. ...

Encountering a error with NextJS during the initial npm run dev command

My PC seems to be having issues every time I try to create a NextJS application and run it in development mode. I keep encountering this error: Error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use ...

What is the method for accessing a validator that has been declared in a reactive form group while within the scope of a custom

Currently, I have a custom component that I am happy with and it is being used in a reactive form as shown below. private init() { const control4 = new FormControl("yy", Validators.pattern(".{2}")); const control5 = new FormControl("zz", Validators.pa ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

Information sent from TypeScript frontend to Java backend is converted into a LinkedHashMap

I have a situation where my typescript frontend is communicating with my java backend using REST. Recently, I added a new simple rest endpoint but encountered an issue when trying to cast the sent object properly because the body being sent is a LinkedHash ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

Using Typescript to combine strings with the newline character

Currently, I am delving into Angular2 and facing the challenge of creating a new line for my dynamically generated string. For example: input: Hello how are you ? output: Hello how are you? Below is the code snippet: .html <div class="row"> ...

Tips for reusing a Jest mock for react-router's useHistory

When testing my code, I set up a mock for the useHistory hook from react-router-dom like this: jest.mock("react-router-dom", () => ({ useHistory: () => ({ length: 13, push: jest.fn(), block: jest.fn(), createHref: jest.fn(), go ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

What is the best way to access a class's private static property in order to utilize it for testing purposes?

Hello, I am currently a beginner in TypeScript and unit testing, so this inquiry may seem elementary to those more experienced. I am attempting to perform unit testing on the code provided below using sinon. Specifically, I am interested in testing whethe ...

Could you please clarify the type of event on the onInputChange props?

I am encountering an issue with using React.ChangeEvent on the mui v4 autocomplete component as I prefer not to use any other method. However, I keep getting an error indicating that the current event is incompatible. const handle = (e: React.ChangeEv ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

Trouble with CORS blocking NextJs from fetching data from Prismic

I'm encountering an issue while trying to fetch and display lists of my content on a simple blog. Every time I attempt to run the code, it gives me a CORS error message stating that my request has been blocked. It's frustrating because all I wan ...