简体   繁体   English

如何使用Webpack独立捆绑JS和CSS文件?

[英]How to bundle JS and CSS file independently with Webpack?

I have a few JS and SCSS files. 我有一些JS和SCSS文件。 I need Webpack 4 to bundle each JS entry to one JS file and each SCSS entry to one CSS file. 我需要Webpack 4将每个JS条目捆绑到一个JS文件中,并且将每个SCSS条目捆绑到一个CSS文件中。 The JS files don't import the SCSS files. JS文件不会导入SCSS文件。 I try to do it with the following webpack.config.js : 我尝试使用以下webpack.config.js来做到这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'
    })
  ]
};

It works fine, Webpack puts the compiled files to the dist directory. 它工作正常,Webpack将编译后的文件放入dist目录。 But it also creates an excess dummy JS file for each SCSS file in the dist directory: 但是它还会为dist目录中的每个SCSS文件创建一个多余的伪JS文件:

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
  ...

How to make Webpack not to create the excess JS files? 如何使Webpack不创建多余的JS文件?

It is because for each property in the entry object ,The js file is created in output destinations. 这是因为对于条目对象中的每个属性,都在输出目标中创建了js文件。

output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') },

Webpack creating dummy js when css is an entry point is a known bug, which has not been fixed yet. 当css作为入口点时,Webpack创建虚拟js是一个已知的错误,尚未修复。

Also having multiple entry files in the entry configuration will also affect treeshaking capabilties 在条目配置中还具有多个条目文件也将影响树状交换功能

Use the ignore-emit-webpack-plugin Webpack plugin to not create the excess file. 使用ignore-emit-webpack-plugin Webpack插件不创建多余的文件。 First install it by running in a console: 首先通过在控制台中运行来安装它:

npm install --save-dev ignore-emit-webpack-plugin

Then add it to your Webpack configuration: 然后将其添加到您的Webpack配置中:

const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');

module.exports = {
  // ...
  plugins: [
    // ...
    new IgnoreEmitPlugin(['styleBaz.js', 'styleBaq.js']) // Or simply: new IgnoreEmitPlugin(/^style.*\.js$/)
  ]
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM