![](/img/trans.png)
[英]CSS not added to /dist folder using Webpack 4 and MiniCssExtractPlugin
[英]Webpack, generate individual CSS file for each imported CSS file with MiniCssExtractPlugin
我是 Webpack(和开发人员)的新手,我正在尝试弄清楚如何使用 Webpack 和一些插件将任何 CSS 导入分隔到单个 CSS 链接标签中。
这是我的 webpack-config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: {
index: ['./src/assets/js/script.js'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'assets/js/[name].bundle.js',
assetModuleFilename: 'assets/images/[name][ext][query]',
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
chunks: ['index'],
title: "~we don't talk about bruno~",
filename: 'index.html',
template: './src/index.html',
}),
new MiniCssExtractPlugin({
filename: 'assets/css/[name].css',
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [
// 2. remove CSS from JS and save into an external file
{ loader: MiniCssExtractPlugin.loader },
// 1. generate CSS into CommonJS
'css-loader',
],
},
{
test: /\.scss$/i,
use: [
// 3. remove CSS from JS and save into an external file
{ loader: MiniCssExtractPlugin.loader },
// 2. generate CSS into CommonJS
'css-loader',
// 1. tranpile SCSS into CSS
'sass-loader',
],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
};
这是我的 JavaScript 文件:
import '../css/style.scss';
import 'animate.css';
我知道 Webpack 是一个捆绑器,我理解它,但是否有可能单独生成index.css
和animate.css
并将其链接到 HTML? 或者可能使用另一个插件并在 Webpack 配置中指定animate.css
。
您可以使用webpack.config.js
的optimization
条目。 你可以在你的webpack.config.js
中的plugins
数组之后添加这个条目,例如:
optimization: {
moduleIds: "deterministic",
splitChunks: {
cacheGroups: {
styles: {
test: /animate.css/
name: "animate",
type: "css/mini-extract",
chunks: "all",
enforce: true,
},
},
},
},
上述配置将为animate.css
生成一个单独的文件。 但是,它不会为每个 CSS 文件导入生成单独的 CSS 文件。 这与模块捆绑器的用途相反。
通常我们所做的是将我们编写的代码与来自node_modules
的代码分开,编写以下配置:
optimization: {
moduleIds: "deterministic",
splitChunks: {
chunks: "all",
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "all",
},
styles: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
type: "css/mini-extract",
chunks: "all",
enforce: true,
},
},
},
},
这样,除了您通常拥有的内容之外,您还可以获得vendors.js
和vendors.css
来获取来自node_modules
的内容。 请参阅 Webpack 官方文档中的代码拆分以了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.