gpt4 book ai didi

reactjs - 从 Create-React-App 升级到 Next.js - CSS 样式表不起作用

转载 作者:行者123 更新时间:2023-12-03 14:07:18 28 4
gpt4 key购买 nike

最近我们发现我们的 React 项目必须使用 SSR。我检查了我所知道的每一种方法,并几乎测试了我在媒体和其他网站上找到的所有方法。经过大量工作后,我决定我们必须迁移到 Next JS。

虽然迁移一切的过程都很好,但对于样式表来说。

在我们应用的旧版本中,我们使用 webpack 将样式与项目捆绑在一起,一切都很好。

这是 webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const port = process.env.PORT || 3000;
const extractSCSS = new ExtractTextPlugin('./[name].css');

// const UglifyJS = require('uglifyjs-webpack-plugin');
module.exports = {

mode: 'development',
output: {
filename: 'bundle.[hash].js',
publicPath: '/'
},
devtool: 'source-map',
module: {
rules: [

// First Rule

{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader'],

},

// Second Rule

{
test: /\.scss$/,
use: ['css-hot-loader'].concat(extractSCSS.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader?sourceMap',
options: { alias: { '../img': '../public/img' }, sourceMap: true }
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
}))
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},

{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
},
plugins: [

new HtmlWebpackPlugin({
template: 'public/index.html',
favicon: 'public/favicon.ico'

}),


extractSCSS,

],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
}
};

迁移应用程序后,我的 next.config.js 如下所示:

// next.config.js
const withSass = require('@zeit/next-sass')
const withCSS = require('@zeit/next-css')

module.exports = withCSS( withSass(
{
webpack(config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
},
)

return config
},

}
))

问题是一切都正确呈现,但其中没有样式表并且不包含任何样式。有谁可以帮我解决这个问题吗?

最佳答案

对于仅使用node_modules中的CSS,你不需要这个花哨的配置。

3 个简单步骤:

  1. 安装 next-css 插件:
npm install --save @zeit/next-css
  • 在根目录中创建 next.config.js,其中包含以下内容:
  • // next.config.js 
    const withCSS = require('@zeit/next-css')

    module.exports = withCSS({
    cssLoaderOptions: {
    url: false
    }
    })
  • 现在您应该能够从 node_modules 导入样式表,如下所示:
  • import 'bootstrap-css-only/css/bootstrap.min.css';

    注意:使用 Next v 8+

    背景:我花了几个小时尝试简单地导入作为 node_module 安装的 CSS,各种解决方案大多是 hacky 解决方法,但如上所示,有一个简单的解决方案。它由核心团队成员之一提供:https://spectrum.chat/next-js/general/ignoring-folders-files-specifically-fonts~4f68cfd5-d576-46b8-adc8-86e9d7ea0b1f

    关于reactjs - 从 Create-React-App 升级到 Next.js - CSS 样式表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52688284/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com