javascript - 无法在 React Web App 中导入 css 文件

标签 javascript html css reactjs webpack

我想将一个纯 css 文件导入到我的 React Web 应用程序中,到目前为止我已经尝试过这种方式:

在我的 index.tsx 中我有:

import * as React from "react"
import '../assets/styles.css';

在我的 webpack.config.js 中我有:

var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: [
        "./src/index.tsx"
    ],

    output: {
        filename: "bundle.js",
        publicPath: "/",
        path: path.resolve(__dirname, "dist")
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    plugins: [
        new webpack.NoEmitOnErrorsPlugin(),
        new ExtractTextPlugin('app.css')
    ],

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, use: ["awesome-typescript-loader"] },
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, enforce: "pre", use: "source-map-loader" }
        ],
        loaders: [ {
            test: /\.js|.jsx?$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
        }, {
            test: /\.(jpe?g|png|gif|svg)$/i,
            loaders: [
                'file?hash=sha512&digest=hex&name=[hash].[ext]',
                'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
            ]
        },
        { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }
        ]
    }
};

错误:

ERROR in ./src/assets/styles.css Module parse failed: Unexpected character '@' (1:11) You may need an appropriate loader to handle this file type.

我是否也可以直接从 index.html 引用样式?如果是这样,我将如何引用我的 styles.css?我已经尝试过这样的事情:

但这是行不通的,我不知道 styles.css 的路径是什么,你在我的目录中将它作为 src/assets/styles.css。

最佳答案

您需要将此添加到您的规则中:

{
  test: /\.css$/,
  use: [
    'style-loader',
    'css-loader',
  ]
}

关于javascript - 无法在 React Web App 中导入 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910571/

相关文章:

Javascript:更改第一个子样式

javascript - 如何在 HTML 页面上使用这个 javascript?

javascript - Ajax、长轮询、多用户、聊天到达

javascript - 如果任一 div 可见,jQuery 将隐藏

javascript - 如何使用 jquery 选项卡加载多个菜单

html - 使用 css 选择器从所有行中选择第一个 td

php - 日常风采网站

html - 如何向下或向上移动 div?

javascript - 在 JWPlayer 5.9 中突出显示当前事件的播放列表项

iframe 中的 HTML anchor 在 Chrome 或 Safari 中不起作用