Utilizing NextJs Webpack to incorporate NextJs project B into project A as a module or framework

In my latest project, I have developed Project B using NextJs as an independent module/framework. This project includes components/gui and css/scss files that are bundled into bundle.js with Webpack.

Now, when installing Project B within Project A, the expectation is for Project A's common css styles to take priority over Project B's css styles. If not, default Project B css styles should be used.

Currently, I have successfully created a bundle for Project B. However, I am facing two main issues:

Q1) How can I import Project B's components into Project A? Q2) I am encountering a warning in the build logs - how do I address this?

This is the webpack.development.config.js file that I am using, which is invoked through package.json:

"scripts": {
    "dev": "next dev",
    "build": "webpack --config webpack.development.config.js --stats detailed",
    "start": "next start",
    "lint": "next lint"
  },

Here is the content of webpack.development.config.js:

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.[contenthash].js',
    path: path.resolve('./dist'),
  },
  mode: 'development',
  resolve: {
    extensions: [ '.js', '.jsx', '.ts', '.tsx' ],
  },
  // Module rules...
  plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
    }),
  ],
}

https://i.sstatic.net/kYLN6Hb8.png

Answer №1

Providing a solution to the initial question, (next js build tool operates smoothly without requiring an external build tool), you can create a separate webpack configuration file or modify the existing next.config.mjs in either project A or project B where you intend to install project B as a dependency. In my case, I am utilizing Next.JS version 14.2.12.

Below is the content of the next.config.mjs script:

import path from 'path';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';

/** @type {import('next').NextConfig} */
const nextConfig = ({
  
  webpack: (config) => {
    // Add custom loader for .tsx files
    config.module.rules.push({
      test: /\.tsx?$/, // For .ts and .tsx files
      use: [
        {
          loader: 'babel-loader',
          options: {
            presets: ['next/babel'], // Use Next.js Babel preset
          },
        },
      ],
    });

    // Add custom loader for .scss files
    config.module.rules.push({
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader',
          options: {
            publicPath: (resourcePath, context) => {
              return path.relative(path.dirname(resourcePath), context) + "/";
            },
          },
          options: {
            
            modules: {
              namedExport: false,
              localIdentName: "[name]__[contenthash]__[local]",
            },
            importLoaders: 1,
          },
        },
      ],
      include: /\.module\.css$/,
    });

    config.module.rules.push({
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader, 'css-loader',
      ],
      exclude: /\.module\.css$/,
    });

    config.module.rules.push({
      test: /\.scss$/,
      use: [
        MiniCssExtractPlugin.loader, 
        {
          loader: 'css-loader',
          options: {
            publicPath: (resourcePath, context) => {
              return path.relative(path.dirname(resourcePath), context) + "/";
            },
          },
          options: {
            
            modules: {
              namedExport: false,
              localIdentName: "[name]__[contenthash]__[local]",    
            },
            importLoaders: 1,
          },
        },
        'sass-loader'
      ],
      include: /\.module\.scss$/,
    });

    config.module.rules.push({
      test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'
        ],
        exclude: /\.module\.scss$/,
    });

    // Add MiniCssExtractPlugin to the Webpack plugins array
    config.plugins.push(
      new MiniCssExtractPlugin({
        filename: 'static/css/[name].[contenthash].css',
        chunkFilename: 'static/css/[id].[contenthash].css',
      })
    );

    return config;
  },
});

export default nextConfig;

In project B, simply execute the default npm run build command without any additional configurations, publish it on npm, and then install it in project A.

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

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

What is the best method for adding a background image to a jumbotron in my Django project?

I have been struggling with this issue for some time now. Currently, I am working on a Django project and I need to add an image as the background in the jumbotron section. home.html {% extends 'blog/base.html' %} {% load static %} {% bl ...

Tips for avoiding a large <ul> element from spilling over the body in a flexbox design

I struggled to articulate the problem I am facing, and I apologize if it's still unclear So, in my app, I have 3 cards, and the 2 side ones contain lists (<ul>) that can become quite lengthy. I want the scrollbar to appear on the <ul> its ...

How can I dynamically adjust the size of an image in a directory based on its filename with php?

Is it possible to resize a specific image in a folder by its name using PHP? ..................................................................................................................................................................... I have trie ...

The poker table designed with CSS does not resize effectively when displayed in smaller dimensions

I have put together a CSS poker table design that I am quite happy with at the moment: https://jsfiddle.net/78fcs01m/3/ CSS: .poker-container { display: grid; width: 100vw; height: 100vh; .poker-table { justify-self: cent ...

Steps to resolve columns wrapping around the screen too tightly instead of properly fitting into place

I am currently working on a website and trying to display an image preview alongside a block of text using Bootstrap 4. However, I am facing an issue where the columns wrap around the screen, resulting in a row that appears two columns tall. Despite my at ...

The navigation/hamburger icon vanishes after a click on a page link

I'm in the process of creating a single-page scrolling website. However, I am encountering an issue with the navigation bar. Specifically, when I click on a page link from the nav bar at screen widths less than 780px (when the hamburger icon appears), ...

Maintain the alignment of content in the center while expanding background images

I am looking to create a website with a split background effect, similar to the design on this site . I want to maintain a content container width of 980px while achieving this look. I attempted to accomplish this by adding height and background color pro ...

Display a preview window once the image has been chosen

I have created an image preview div to show the selected image's thumbnail. Everything was working fine so far. But now, I want this div to be hidden when the page initially loads and only become visible when a user selects an image to upload. Here is ...

Setting up CSS module class names in a Vue project using Vite js configuration

Within my vite.config.ts file, I have specified a configuration for CSS modules. return defineConfig({ ... css: { ... modules: { localsConvention: "camelCase", generateScopedName: "[name]__[local]__[hash:base64:2]" ...

CSS: Struggling with Div Alignment

Here is a visual representation of the issue I am facing: View the screenshot of the rendered page here: http://cl.ly/image/0E2N1W1m420V/Image%202012-07-22%20at%203.25.44%20PM.png The first problem I have encountered is the excessive empty space between ...

Select element's width decreases by 2 pixels following the application of width adjustment via jQuery

After browsing through numerous pages, I finally managed to adjust the width of my textbox and select element using jQuery 2.0. Snippet of Code from my Project: $(document).ready(function(){ $("#Text2").css('width','20 ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

Cryptic mention of visuals post Webpack React compilation

I've been working on my application with webpack and so far things have been improving. It seems like none of my modules are corrupt. I must admit, I was quite surprised when this tool managed to shrink my 150mb React app down to 2mb, even though I do ...

The navigation bar in Bootstrap has unique behavior with links

I am currently in the process of creating a navigation bar using Bootstrap, you can view it here All the links on the navbar are behaving similarly except for the 'Save and exit' link. How can I adjust it to look consistent with the other links? ...

Conceal DIV containers during the loading of the page, and reveal them only upon the selection of Radio Buttons

In my user interface, I have implemented three radio buttons labeled as "Easy," "Medium," and "Hard." Each button is assigned to a distinct Javascript function that manipulates the visibility of corresponding div elements. The main purpose behind this setu ...

Aligning form fields using CSS and Bootstrap 4

I am struggling to center a form on my page. The labels are centered, but the input with the form-control class is not cooperating. Currently, it appears like this... [EDIT: I have identified that the display: block; within form-control is causing the is ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

After a successful sign-in on next-auth.js using next.js middleware, users are automatically redirected to the sign-in page

I have integrated next-auth.js with Google as the login provider and Django as the backend to protect pages in my Next.js application. In order to achieve this, I am trying to integrate next-auth.js with Next.js middleware. Reference link The issue I&apos ...

Difficulty encountered in setting margin to 0 in Bootstrap 4 framework

Upon observation, I found that setting margin: 0px had no effect. Even after specifying a margin of 0 for left and right, the screenshot still displayed the margin. https://i.sstatic.net/mkYsO.png Initially, I checked for any conflicting classes or IDs c ...