簡體   English   中英

Next.js 全局 CSS 無法從自定義文件以外的文件導入<app></app>

[英]Next.js Global CSS cannot be imported from files other than your Custom <App>

我的 React App 運行良好,也使用全局 CSS。

我運行npm i next-images ,添加圖像,編輯next.config.jsran npm run dev ,現在我收到這條消息

Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.
Read more: https://err.sh/next.js/css-global

我已經檢查了文檔,但由於我是 React 的新手,所以我發現這些說明有點令人困惑。

另外,為什么現在會發生這個錯誤? 您認為它與 npm 安裝有什么關系嗎?

我試圖刪除我添加的新文件及其代碼,但這並不能解決問題。 我還嘗試了閱讀更多:建議的內容。

我的最高層組件。

import Navbar from './Navbar';
import Head from 'next/head';
import '../global-styles/main.scss';

const Layout = (props) => (
  <div>
    <Head>
      <title>Bitcoin Watcher</title>
    </Head>
    <Navbar />
    <div className="marginsContainer">
      {props.children}
    </div>
  </div>
);

export default Layout;

我的 next.config.js

// next.config.js
  const withSass = require('@zeit/next-sass')
  module.exports = withSass({
  cssModules: true
})

我的 main.scss 文件

@import './fonts.scss';
@import './variables.scss';
@import './global.scss';

我的 global.scss

body {
  margin: 0;
}
:global {
  .marginsContainer {
    width: 90%;
    margin: auto;
  }
}

我覺得最奇怪的是,這個錯誤並沒有改變任何與 CSS 或 Layout.js 相關的東西,而且它以前是有效的?

我已將我的 main.scss 導入移動到 pages/_app.js 頁面,但 styles 仍然沒有通過。 這是 _app.js 頁面的樣子

import '../global-styles/main.scss'

export default function MyApp({ Component, props }) {
  return <Component {...props} />
}

使用內置的 Next.js CSS 加載器(參見此處)而不是舊版@zeit/next-sass

  1. sass替換@zeit/next-sass包。
  2. 刪除next.config.js 或者不要更改其中的 CSS 加載。
  3. 按照錯誤消息中的建議移動全局 CSS。

由於 Next.js 9.2 必須在自定義<App>組件中導入全局 CSS。

// pages/_app.js

import '../global-styles/main.scss'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

要將樣式僅添加到特定組件或頁面,您可以使用CSS 模塊的內置支持。 (見這里

例如,如果您有一個組件Button.js ,您可以創建一個 Sass 文件button.module.scss並將其包含在組件中。

當您的文件在命名中有module時, Next.js停止抱怨,例如,更改import '../global-styles/main.scss'; import '../global-styles/main.module.scss'; 將修復警告,您可以將樣式放在global-styles中,或者例如在您的component中。

next.config.js中不需要額外的依賴項/配置。

你可以用你自己的替換那些固執己見(而且過於復雜?)的 NextJs CSS 加載器。 這是一個簡單的全局css:

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex(r => r.oneOf)
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.')
    }
    config.module.rules.splice(cssRulesIdx, 1)

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        experimentalUseImportModule: true,
        filename: 'static/css/[contenthash].css',
        chunkFilename: 'static/css/[contenthash].css',
      })
    )

    config.module.rules.push({
      test: /\.css$/i,
      use: !isServer ? ['style-loader', 'css-loader'] : [MiniCssExtractPlugin.loader, 'css-loader'],
    })
    return config
  },
}

對我來說,問題是因為我在next.config.js文件中使用了兩個 module.exports,如下所示

const withPlugins = require('next-compose-plugins')
const sass = require('@zeit/next-sass')
const css = require('@zeit/next-css')

const nextConfig = {
    webpack: function(config){
    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
    }
}

module.exports = withPlugins([
    [css],
    [sass, {
        cssModules: true
    }]
], nextConfig)

module.exports = {
    env: {
        MONGO_URI = 'your uri'
    }
}

. 1我修改它以改變這樣的導出模塊。

const nextConfig = {
    webpack: function(config){
    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
    },
    env: {
        MONGO_URI: "your uri"
    }
}

2然后我刪除了第二個module.exports

本節點package為其提供了完美的解決方案。 你可以在這里找到它

修復步驟:

1 、添加package:

npm install next-remove-imports
or
yarn add next-remove-imports

2.在你的next.config.js 中添加這個包裝器變量

const removeImports = require('next-remove-imports')({
   test: /node_modules([\s\S]*?)\.(tsx|ts|js|mjs|jsx)$/,
   matchImports: "\\.(less|css|scss|sass|styl)$"
 });

它所做的只是為tsx|ts|js|mjs|jsx文件重新啟用全局樣式導入規則

3.用這個next-remove-imports包裝器包裝你的下一個配置導出。 像這樣:

module.exports = removeImports((nextConfig)

4.現在重新啟動你的 React 應用程序,你將能夠在任何ts|js|js|jsx|mjs文件或組件中導入 CSS 個文件。

你不需要在next.config.js中做任何事情。

假設您正在使用像 Bootstrap 這樣的全局 css,這意味着它包含的 css 旨在應用於您的整個應用程序以及其中的所有不同頁面。

全局 css 文件必須以一種非常特殊的方式連接到 NextJS。

因此,您需要在pages/目錄中創建_app.js

將文件命名為_app.js

然后在該文件的頂部,您將按以下方式導入 Bootstrap css:

import 'bootstrap/dist/css/bootstrap.css';

然后,您將添加以下內容:

export default ({ Component, pageProps }) => {
  return <Component {...pageProps} />;
};

那么該代碼中發生了什么?

好吧,在幕后,每當您嘗試使用 NextJS 導航到某個不同的頁面時,NextJS 都會從您pages/目錄中的不同文件之一導入您的組件。

NextJS 不只是將您的組件顯示在屏幕上。

相反,它將它包裝在自己的自定義默認組件中,並在 NextJS 內部稱為 App。

您通過定義_app.js的是定義您自己的自定義應用程序組件。

因此,每當您嘗試訪問瀏覽器內的路由或根路由時,NextJS 都會導入該給定組件並將其作為Component屬性傳遞給AppComponent

因此,那里的Component等於您在pages/目錄中擁有的任何組件。 然后pageProps將成為您打算傳遞給pages/內文件的組件集。

長話短說,這個東西就像你試圖在屏幕上顯示的組件的薄包裝。

為什么你必須定義這個?

好吧,如果你想在項目中包含一些全局 css,例如 Bootstrap 是一個全局 css,你只能將全局 css 導入到_app.js文件中。

事實證明,如果您嘗試訪問其他組件或其他頁面,NextJS 不會加載甚至解析這些文件。

因此,您可能在其中導入的任何 css 都不會包含在最終的 HTML 文件中。

所以你有一個必須包含在每個頁面上的全局 css,它必須被導入到應用程序文件中,因為它是唯一保證每次用戶訪問你的應用程序時都會加載的文件。

不要忘記,除了在_app.js中導入 css 之外,您還必須在終端中運行npm install bootstrap

您可以在此處閱讀更多信息: https ://nextjs.org/docs/messages/css-global

將此添加到您的_app.js

import '../styles/globals.css'

嘗試在您的 scss 文件名中包含“.module”。

main.module.scss更改為main.scss

例子:

import styles from './todolist-profile-info.module.scss'

對我來說,我收到了這個錯誤,因為我對項目的父文件夾使用了不正確的命名,在其中使用了特殊字符,

project#1,

刪除特殊字符並將文件夾名稱更改為類似project-1,錯誤就消失了。

你必須為每個組件 css/scss 編寫 navbar.module.css/scss/sass.Next js 不會編譯 navbar.css/scss/sass。 如果希望我的回答對你有幫助!。

就我而言,navbar.module.css 中有錯字我寫過 navbar.moduile.css

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM