webpack非输入文件名

时间:2019-04-11 14:06:58

标签: webpack sass-loader mini-css-extract-plugin

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const fs = require('fs');



module.exports = {
  mode: 'production',
  context: path.resolve(__dirname, 'app'),
  devServer: {
    host: "www.mydomain.local",
    compress: true,
    https: {
      key: fs.readFileSync('https.key'),
      cert: fs.readFileSync('https.crt')
    }
  },
  optimization: {
    minimizer: [new UglifyJsPlugin({})],
  },
  entry: {
    blog: path.resolve(__dirname, 'src', 'blog.js')
  },
  output: {
    path: path.resolve(__dirname, 'web', '_assets'),
    publicPath: path.resolve(__dirname, 'web', '_assets'),
    filename: "js/[name].[hash].bundle.js"
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "css/[name].[hash].bundle.css",
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader"
        ]
      }
    ]
  }
};

如您所见,我在webpack配置“博客”中只有一个条目,该条目解析为具有以下内容的./src/blog.js

import('./css/blog.scss')

console.log(1)

当我运行webpack --config webpack.config.js时,它会按预期的./web/_assets/js/blog.21342i1j4h1kj.bundle.js生成,其中包含console.log(1)

但是奇怪的是它还可以构建./web/_assets/js/1.21342i1j4h1kj.bundle.js./web/_assets/css/1.21342i1j4h1kj.bundle.js

额外的JS文件包含

(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[,function(n,w,o){}]]);

,而1.css文件包含了由css编译的css的sass。

我的问题是:

  • 为什么多余的JS文件存在?
  • 为什么css文件未称为blog.21342i1j4h1kj.bundle.css
  • 如何更改配置以解决此问题?

1 个答案:

答案 0 :(得分:0)

原来1.js是一个webpack动态导入功能,这是因为css是在blog.js文件内部导入的。我最终只是对webpack.config.js条目部分进行了此更改

blog: [
      path.resolve(__dirname, 'src_new', 'blog.js'),
      path.resolve(__dirname, 'src_new', 'blog.scss')
    ],

,其余部分由插件配置完成:

plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].[hash].bundle.css",
    })
  ],

这将导致blog.5903ffe3afb455f5e5d0.bundle.css中定义的blog.5903ffe3afb455f5e5d0.bundle.jsoutput.path