如果出现捆绑包,样式加载器将不起作用

Style loader does not working if bundle is presented

如果我使用开发模式,样式加载器工作正常。但是当我构建项目并且我有 dist 文件夹时,我在 head 标签中看不到 style 标签。有趣的是,仅当 bundle.js 文件出现在 dist 中时,我才看不到样式标签。

我的配置:

const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const extractSASS = new ExtractTextPlugin({
  filename: './css/[name].css',
  allChunks: true
});

var entry = [
  'babel-polyfill',
  './src/index.js'
]

var output = {
  path: path.join(__dirname, 'dist'),
  filename: 'js/bundle.js',
  publicPath:'/static/'
}

var rules = [
  {
    use: 'babel-loader',
    include: __dirname,
    exclude:[
      path.resolve(__dirname, "node_modules"),
    ],
    test: /\.js$/
  },
  {
    test: /\.(scss|css)$/,
    use: process.env.NODE_ENV == 'production'
      ? extractSASS.extract({
        fallback: 'style-loader',
        use: ['css-loader','sass-loader']
      })
      : [ 'style-loader', 'css-loader', 'sass-loader']
  }
]

if(process.env.NODE_ENV != 'production') entry.push('webpack-hot-middleware/client')

const dev = {
  devtool: 'cheap-module-eval-source-map',
  entry: entry,
  output: output,
  plugins: [
    extractSASS,
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    rules: rules
  }
}

const prod = {
  entry: entry,
  output: output,
  plugins: [
    extractSASS,
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new CopyWebpackPlugin([{from:'src/img', to:'img'}]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ],
  module: {
    rules: rules
  }
}

module.exports = process.env.NODE_ENV == 'production' ? prod : dev;

有人知道什么会导致问题吗?谢谢。

问题出在 HMR 中。正如您在配置中看到的,在生产中我们不使用 HMR。所以,当我们的包被创建时,我们的标记抓住了这个包。这个 bundle 对 sass 中的变化一无所知(因为它不包含 hmr 的东西),所以,我们无法在脑海中看到样式标签。 解决方案是在开发模式下删除 运行 之前的包。