我认为我正确地遵循了文档,但它根本不起作用。
我想要的是生成一个css文件,而不是在带有js的样式标签中加载它。
在我的src目录::“scss / custom.scss”和“style.scss”中,它们都不会在输出中生成。
编辑:src代码:https://github.com/marcosroot/webpackexample
我的设置是:
const path = require('path');
const BundleTracker = require('webpack-bundle-tracker');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = true;
module.exports = {
entry: [
'./src/toggle_menu.js',
'./src/calls_apis.js'
],
output: {
path: path.resolve(__dirname, "dist"),
filename: devMode ? 'main.js' : 'main.[hash].js',
},
plugins: [
new BundleTracker({
filename: './webpack-stats.json'
}),
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css'
})
],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
},
{
test: /\.scss$/,
include: path.resolve(__dirname, 'scss/custom.scss'),
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
]
}
]
},
}
我认为您的问题来自于配置中的错误路径解决方案:
include: path.resolve(__dirname, 'scss/custom.scss'),
这意味着webpack只包含位于{root}/scss/custom.scss
下的资源,并且根据您的解释,我认为正确的路径应该是{root}/src/scss/custom.scss
。
因此,要在{root}/src/scss/custom.scss
文件夹下包含两个文件{root}/src/styles.scss
和src
以及任何其他scss文件,您可以使用:
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
},
{
test: /\.scss$/,
include: /src/, // <-- Change here ---------------------
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
]
}
]
},
如果你非常确定你的项目或节点模块中没有其他漫游scss文件可以找到并且不应该同时捆绑(你可能就是这种情况),你也可以简单地删除include
选项。
您还可以通过在路径解析中添加src来提供这两个文件的数组:
include: [
path.resolve(__dirname, 'src/scss/custom.scss'),
path.resolve(__dirname, 'src/styles.scss'),
]
******编辑*******
在你的评论和你的回购之后,还有一些错误:
postcss-loader
不包含在dev依赖项中,也没有配置它include
选项。它只是意味着只会处理与包含测试匹配的资源,就像在该规则中配置的那样。您仍然需要在脚本中的某个位置要求scss文件。我有forked your repo并在call_api.js(你的一个入口点)中使用scss import设置了正确的配置。构建,你会在dist文件夹中看到css文件(我已经为postcss设置了一个愚蠢的cssnano配置,这将被解析为苛刻)
您需要在文件名中提供相对路径,或在加载程序配置publicPath: '../'
中指定https://www.npmjs.com/package/mini-css-extract-plugin#minimal-example
在我的项目中,我有
new MiniCssExtractPlugin({filename: DEV ? '../css/styles.css' : '../css/styles-[contenthash].css'}),
文档提供了公共路径的示例
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../'
}
},
"css-loader"
]
}
]
}
}