webpack-contrib / mini-css-extract-plugin

Lightweight CSS extraction plugin
MIT License
4.65k stars 389 forks source link

CommonJS for css files in HtmlWebpackPlugin template #1046

Closed kolesnikanton closed 1 year ago

kolesnikanton commented 1 year ago

Bug report

I'm getting this error when I use the commonjs import for css files in template.js which is used in HtmlWebpackPlugin:

ERROR in   Error: Child compilation failed:
  No template for dependency: CssDependency
  CodeGenerationError: No template for dependency: CssDependency

I don't see any problems when I use the ES6 import. I also don't see any problems when I use the commonjs import for .js files. I believe the problem somewhere in MiniCssExtractPlugin.

Actual Behavior

No template for dependency: CssDependency when use require('*.css') in template.js for HtmlWebpackPlugin

Expected Behavior

Works as ES6

How Do We Reproduce?

template.js

require('./styles.css'); // doesn't work
// import './styles.css'; // works

const template = `
  <!DOCTYPE html>
  <html lang="en">
    <head></head>
    <body></body>
  </html>
`;

export default template;
// module.exports = template; // doesn' care

webpack

...
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = function config() {
  return {
    entry: {
      test: './src/pages/test/test.js',
    },
    output: {
      filename: '[name]/[name].js',
      path: path.resolve(__dirname, 'dist'),
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'test/index.html',
        template: './src/pages/test/template.js',
        chunks: ['test'],
      }),
      new MiniCssExtractPlugin({ filename: '[name]/[name].css' })
    ],
    module: {
      rules: [
        {
          test: /\.js$/,
          include: path.resolve(__dirname, 'src'),
          use: {
            loader: 'babel-loader',
            options: { presets: ['@babel/preset-env'] },
          },
        },
        {
          test: /\.html$/i,
          loader: 'html-loader',
        },
        {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader'],
        },
      ],
    },
  };
};

Please paste the results of npx webpack-cli info here, and mention other relevant information

  System:
    OS: macOS 13.4.1
    CPU: (8) arm64 Apple M1
    Memory: 106.63 MB / 8.00 GB
  Binaries:
    Node: 18.15.0 - ~/.nvm/versions/node/v18.15.0/bin/node
    npm: 9.5.0 - ~/.nvm/versions/node/v18.15.0/bin/npm
  Browsers:
    Chrome: 115.0.5790.114
    Safari: 16.5.2
  Packages:
    babel-loader: ^9.1.2 => 9.1.3 
    css-loader: ^6.3.0 => 6.8.1 
    css-minimizer-webpack-plugin: ^5.0.0 => 5.0.1 
    html-loader: ^4.2.0 => 4.2.0 
    html-webpack-plugin: ^5.3.2 => 5.5.3 
    style-loader: ^3.2.1 => 3.3.3 
    webpack: ^5.53.0 => 5.88.2 
    webpack-cli: ^5.0.1 => 5.1.4