Webpack generates js files with css / scss files

心已入冬 提交于 2020-07-09 05:14:32

问题


Description

In webpack I am using mini-css-extract-plugin:

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

To load scss files in chunk files:

{
  test: /\.scss$/,
  use: [
    { loader: MiniCssExtractPlugin.loader, options: {
        hmr: isdev,
        reloadAll: true
      }
    },
    "css-loader",
    "sass-loader",
  ]
}

When I load a scss with an dynamic import:

import(/* webpackChunkName: "test" */ 'test.scss')

It will generate a test.[hash].css containing the styles and a test.[hash].js:

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[15],{

/***/ 81:
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ })

}]);

Problem

I want to minimize the delay and loaded files so I find it redundant to have a nearly empty test.[hash].js file.

Do you have a way to either include the scss in the js file (see Idea 1) or to not emit/use the nearly empty js file?

Idea 1: not using mini-css-extract-plugin

My first idea was not using mini-css-extract-plugin for dynamic imported scss, but this will include a lot css-base stuff in the js (https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/255).


回答1:


Here is an extract of code that could interrest you. It's coded in live here, so there is maybe some error I don't know.

I use an alternative way but nearby inside my own project.

The behaviour is :

  1. Use the Event Hook Plugin and call it when the webpack is done
  2. Loop through each file
  3. If file is css and have the same name as with js extension
  4. Then remove the js file

    const EventHooksPlugin = require('event-hooks-webpack-plugin');
    const path             = require('path');
    const fs               = require('fs');
    const _                = require('underscore');
    
    plugins: [
        new EventHooksPlugin({
                done: () => {
                        const publicDir = __dirname + '/public';
                        const files     = fs.readdirSync(publicDir);
    
                        _.each(files, file => {
                              if (path.extname(file) !== '.css') { return ;}
    
                              const fileJs = file.replace('.css', '.js');
    
                              if (!fs.existsSync(fileJs)) {return;}
    
                              fs.unlinkSync(fileJs);
                        });
                }
        })
    ]
    


来源:https://stackoverflow.com/questions/56937912/webpack-generates-js-files-with-css-scss-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!