首页 文章

Webpack:样式加载器和css-loader无法正常工作

提问于
浏览
1

我是webpack的新手,我只是使用一些加载器为一个反应项目做了一个简单的webpack配置 . 我希望能够像在style-loader / css-loader的doc中那样导入css文件 .

但是,我无法使其发挥作用 . 经过几次尝试,我在这里寻求帮助:)我错过了什么吗?

当我检查构建文件夹时,除了从导入css文件的行之外,我的所有代码都被很好地编译了 .

这是我的webpack配置:

const path = require('path');
    const PROD = JSON.parse(process.env.NODE_ENV || '0');

    module.exports = {
        devtool: PROD ? 'cheap-module-source-map' : 'eval',
        entry: ["./app/index.jsx"],
        output: {
            path: path.join(__dirname, "build"),
            filename: "bundle.js"
        },
        // extensions to resolve when a require is done
        resolve: {
            extensions: [".js", ".json", ".jsx"]
        },
        module: {
            // the loaders list (they are executed in the inverse order)
            rules: [
                // loader for all js and jsx files
                {
                    enforce: "pre", // make sure the eslint is used before babel
                    test: /\.js$/,
                    include: path.join(__dirname, 'app'),
                    exclude: /node_modules/,
                    loader: "eslint-loader",
                },
                {
                    test: /\.js$/,
                    include: path.join(__dirname, 'app'),
                    exclude: /node_modules/,
                    loader: "babel-loader",
                },
                // loaders for css files
                {
                    test: /\.css$/,
                    use: [ 'style-loader', 'css-loader' ]
                },
                // loaders for other files
                {
                    exclude: [/\.js$/, /\.html$/, /\.json$/],
                    options: {
                        name: 'static/media/[name].[hash:8].[ext]',
                    },
                    loader: "file-loader"
                },
            ],
        },
        plugins: PROD ? [
            // uglify the js files if in production
            new webpack.optimize.UglifyJsPlugin({
                minimize: true,
                compress: {
                    warnings: false
                }
            })
        ] : []
    };

这是我的js文件,它从同一目录导入一个简单的style.css文件:

import React from 'react';
import './style.css';

const App = props => {
    return [
        <h1 className="title">hello</h1>
    ]
};

export default App;

还有我的style.css文件:

.title {
    margin-top: 20px;
}

1 回答

  • 0

    您可以尝试这种语法,适合我:

    module: {
            rules: [
                {
                    test: /\.css$/,
                    use: [
                        {loader: 'style-loader'},
                        {loader: 'css-loader',
                        options: { url: false } // tell css-loader to not package images referenced in css. perhaps re-activate this for base64 injection
                        },
                    ] // use
                }
            ] // rules
        }, // module
    

相关问题