无法在webpack 4中加载css文件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (159)

给定以下WebPack 4配置:

const path = require('path')
const webpack = require('webpack')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const devMode = process.env.NODE_ENV !== 'production'
const devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
})

module.exports = {
    mode: "development",
    entry: [
        'webpack-dev-server/client?http://0.0.0.0:3000',
        'webpack/hot/only-dev-server',
        "./app/app.js"
    ],
    output: {
        path: path.join(__dirname, "build"),
        filename: "bundle.js"
    },
    devtool: 'eval-source-map',
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            { 
                test: /\.jsx|\.js?$/, 
                loader: 'babel-loader',
                options: {
                    plugins: [
                        'react-hot-loader/babel'
                    ]
                },
                exclude: /node_modules/},
            {
                test: /\.jsx|\.js$/,
                exclude: /node_modules/,
                use: [
                'babel-loader?' + JSON.stringify({presets: ['env', 'react']}),
                {
                    loader: 'eslint-loader'
                }]
            },
            {
                test: /\.css$/,
                include: /stylesheets|node_modules/,
                use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
            },
            {
                test: /\.scss$/,
                include: /stylesheets/,
                use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ]
            },
            {
                test: /\.(jpg|png|gif|eot|woff|ttf|svg)/,
                loader: "file"
            }
        ]
    },
    devServer: {
        contentBase: "./build",
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        devFlagPlugin,
        new webpack.NoEmitOnErrorsPlugin()
    ]

};

我试图从app.js中的/stylesheets/app.css in app.js:

require('./stylesheets/app.css')
let routes = (
    <div className="app">
        <Router>
            <div>hello</div>
        </Router>
    </div>
)

render(routes, document.getElementById('root'))

app.css文件定义为:

html {
    font-family: "Open Sans",Arial,sans-serif;
    font-size: 20px;
    height: 100%;
}

但是当我开始这个项目的时候:

webpack-dev-server --host 0.0.0.0 --port 3000 --hot --progress --colors

内容没有与其关联的样式。

我在WebPack配置中遗漏了什么吗?

提问于
用户回答回答于

如果其他人陷入同样的问题,下面是CSS/SCSS加载器的正确配置:

{
    test: /\.css$/,
    include: /stylesheets|node_modules/,
    use: ["style-loader", "css-loader"]
},
{
    test: /\.scss$/,
    include: /stylesheets/,
    use: [ 'style-loader', 'css-loader', 'sass-loader' ]
}

没有使用MiniCssExtractPlugin.Loader;它只是作为插件使用。

扫码关注云+社区

领取腾讯云代金券