问题描述
我有一些 JS 和 SCSS 文件.我需要 Webpack 4 将每个 JS 条目捆绑到一个 JS 文件中,并将每个 SCSS 条目捆绑到一个 CSS 文件中.JS 文件不导入 SCSS 文件.我尝试使用以下 webpack.config.js
:
I have a few JS and SCSS files. I need Webpack 4 to bundle each JS entry to one JS file and each SCSS entry to one CSS file. The JS files don't import the SCSS files. I try to do it with the following webpack.config.js
:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
scriptFoo: './src/js/scriptFoo.js',
scriptBar: './src/js/scriptBar.js',
// ...
styleBaz: './src/css/styleBaz.scss',
styleBaq: './src/css/styleBaq.scss'
// ...
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(scss|sass)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
})
]
};
工作正常,Webpack 将编译后的文件放到 dist
目录中.但是它也为dist
目录下的每个SCSS文件创建了一个多余的伪JS文件:
It works fine, Webpack puts the compiled files to the dist
directory. But it also creates an excess dummy JS file for each SCSS file in the dist
directory:
webpack.config.js
src/
js/
scriptFoo.js
scriptBar.js
...
css/
styleBaz.scss
styleBaq.scss
...
dist/
scriptFoo.js
scriptBar.js
...
styleBaz.css
styleBaz.js // Excess
styleBaq.css
styleBaq.js // Excess
...
如何让 Webpack 不创建多余的 JS 文件?
How to make Webpack not to create the excess JS files?
推荐答案
使用 ignore-emit-webpack-plugin Webpack 插件不会创建多余的文件.首先通过在控制台中运行来安装它:
Use the ignore-emit-webpack-plugin Webpack plugin to not create the excess file. First install it by running in a console:
npm install --save-dev ignore-emit-webpack-plugin
然后将其添加到您的 Webpack 配置中:
Then add it to your Webpack configuration:
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');
module.exports = {
// ...
plugins: [
// ...
new IgnoreEmitPlugin(['styleBaz.js', 'styleBaq.js']) // Or simply: new IgnoreEmitPlugin(/^style.*\.js$/)
]
};
这篇关于如何用 Webpack 独立捆绑 JS 和 CSS 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!