问题
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 :
- Use the Event Hook Plugin and call it when the webpack is done
- Loop through each file
- If file is css and have the same name as with js extension
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