无法在React Web App中导入CSS文件

时间:2018-10-20 22:19:21

标签: 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') }
        ]
    }
};

错误:

  ./src/assets/styles.css中的

ERROR模块解析失败:意外   字符“ @”(1:11)您可能需要适当的加载程序来处理此问题   文件类型。

我是否还可以直接从index.html引用样式?如果是这样,我将如何引用我的styles.css?我已经试过这样的东西了:

但是这不起作用,我不知道styles.css的路径是什么,您在我的目录中将其命名为src / assets / styles.css。

1 个答案:

答案 0 :(得分:1)

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

function list(names){
   let result = names.map(value => value.name);
   return result.slice(-2).toString().split('&');
}

list([{name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}]);