CSS 未使用 Webpack 4 和 MiniCssExtractPlugin 添加到 /dist 文件夹

CSS not added to /dist folder using Webpack 4 and MiniCssExtractPlugin

问题

Webpack 配置专家能否告诉我为什么在 运行 宁 npm run build 时我无法将我的 css 提取到 dist 文件夹中? 回购在这里:https://github.com/damodog/webpack4-boilerplate

更多信息

总而言之,我一直在努力 Webpack Guide docs,一切进展顺利。 js 和 css 分别通过 <link><script> 标签注入到我的 index.html 文件中。我已经安装了各种加载器、插件等,并将我的配置拆分为公共(共享)、开发和生产文件(根据文档),生活很美好。

我碰巧做了一些调整,包括查看 code splitting dynamic imports、为路径添加别名、将 js 移动到 js 文件夹等,并注意到当我 运行 构建 npm run build 所有突然我的 css 没有被添加到 dist 文件夹中。我恢复了对动态导入内容的试用更改,并尝试恢复其他更改,但仍然遇到同样的问题。令人恼火的是,此时我还没有添加 git,所以没有清楚地了解我所做的 'tweaks' 以找到我更改的内容。

会发生什么

当我 运行 我的监视任务 npm start 时 styles.scss 文件(导入到主 index.js 文件中)被编译成 css 和结果app.css 文件在我的本地主机中查看时被注入 index.html 页面。全是肉汁。 <link href="css/app.css" rel="stylesheet">

当我 运行 npm run build 应该将 css 文件复制到 dist 文件夹时,应该添加哈希 ID 并且应该缩小 css。这是有效的(就像我上面说的),我可以在构建步骤中看到 css 文件(见下面的第一个资产。顺便说一句,忽略这里的 js 捆绑文件与下一个屏幕截图的区别。这是我当时玩代码拆分)。

现在,当我 运行 这个 css 没有捆绑时(见下文)。

我认为这可能与 mini-css-extract-plugin 有关,但我已经根据文档使用 advanced configuration example 配置了它(我已经将他们的示例拆分在一个配置文件中因为我有单独的开发和生产配置文件)。

我真的不明白为什么会这样。 帮助我这样的读者。你是我唯一的帮助...

我克隆了您的存储库并进行了试验。在您的 package.json 中,您设置了:sideEffects: false。这会导致导入的样式表在 tree shaking 过程中丢失。这是 described in the docs:

A "side effect" is defined as code that performs a special behavior when imported, other than exposing one or more exports. An example of this are polyfills, which affect the global scope and usually do not provide an export.

Note that any imported file is subject to tree shaking. This means if you use something like css-loader in your project and import a CSS file, it needs to be added to the side effect list so it will not be unintentionally dropped in production mode

所以将 package.json 中的副作用更改为 "sideEffects: ["./src/scss/styles.scss"],在生产模式下它将输出到目标文件夹。