简体   繁体   English

Webpack 可以从 SCSS 和 Pug 构建多个 HTML 文件吗?

[英]Can Webpack build multiple HTML files from SCSS and Pug?

I've read quite a few tutorials on webpack, but it seems more for creating web apps then for what I'm trying to do so I didn't want to waste any more time if the following isn't possible.我已经阅读了很多关于 webpack 的教程,但是创建 web 应用程序似乎更多,然后是我正在尝试做的事情,所以如果无法进行以下操作,我不想再浪费时间了。

I'm creating websites on a third-party eCommerce system and they have a system of coding out templates that can be used to change the structure of their website.我在第三方电子商务系统上创建网站,他们有一个编码模板系统,可用于更改其网站结构。 Below is an example of one of their templates I would be creating (although there are many types & variations I will need to make, not just a few).下面是我将创建的其中一个模板的示例(尽管我需要制作许多类型和变体,而不仅仅是一些)。

My idea to streamline the creation of these templates is to create a bunch of pug components and place them in the components/ directory.为了简化这些模板的创建,我的想法是创建一堆 pug 组件并将它们放在 components/ 目录中。 Outside of the components directory I want to make higher level pug templates that utilize the components.在组件目录之外,我想制作利用这些组件的更高级别的哈巴狗模板。 Once these have been created, I would build it with NPM and the template files need to be converted to HTML and placed within the /dist folder.创建这些文件后,我将使用 NPM 构建它,模板文件需要转换为 HTML 并放置在 /dist 文件夹中。

Is this hard to do with webpack?这很难用 webpack 做吗?

Structure of the project:项目结构:

src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss

and once built:一旦建成:

dist/
..navcustom-template.html
..customfooter-template.html
..non-template-specific.css

src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss

Sample of a template:模板示例:

<!--
    Section: NavCustom
-->

<style>

    //Template Speific CSS Imports Here

</style>
<script type="text/javascript">

    //Template Speific JS Imports Here

</script>
<header>

    <div class="col-md-4">

        // Social Media Code

    </div>

    <div class="col-md-4">

        // Logo Code

    </div>

    <div class="col-md-4">

        //  Call to Action Code

    </div>

</header>
<nav>

</nav>

You can use these packages ( --save-dev for all):你可以使用这些包( --save-dev ):

Then configure Webpack similar to the following, where index.js is a dummy file you should create if you don't already have an entry.然后像下面这样配置 Webpack,其中index.js是一个虚拟文件,如果您还没有条目,您应该创建它。 Each Pug template you need to process is written in a separate HtmlWebpackPlugin object at the bottom.您需要处理的每个 Pug 模板都编写在底部单独的HtmlWebpackPlugin对象中。

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');

module.exports = {
  entry: ['./src/index.js'],
  output: {
    path: __dirname + '/dist',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.pug$/,
        use: [
          "raw-loader",
          "pug-html-loader"
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/navcustom-template.pug',
      filename: 'navcustom-template.html'
    }),
    new HtmlWebpackPlugin({
      template: 'src/customfooter-template.pug',
      filename: 'customfooter-template.html'
    }),
    new HtmlWebpackPugPlugin()
  ]
}

All Pug mixins (your src/components files) will be included in the output.所有 Pug mixins(您的src/components文件)都将包含在输出中。 This example is tested and working.这个例子已经过测试和工作。


Edit: To dynamically process all Pug files in the src directory use this config:编辑:要动态处理src目录中的所有 Pug 文件,请使用以下配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
const fs = require('fs');

let templates = [];
let dir = 'src';
let files = fs.readdirSync(dir);

files.forEach(file => {
  if (file.match(/\.pug$/)) {
    let filename = file.substring(0, file.length - 4);
    templates.push(
      new HtmlWebpackPlugin({
        template: dir + '/' + filename + '.pug',
        filename: filename + '.html'
      })
    );
  }
});

module.exports = {
  entry: ['./src/index.js'],
  output: {
    path: __dirname + '/dist',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.pug$/,
        use: [
          "raw-loader",
          "pug-html-loader"
        ]
      }
    ]
  },
  plugins: [
    ...templates,
    new HtmlWebpackPugPlugin()
  ]
}

This uses fs.readdirSync to get all Pug files in a directory.这使用fs.readdirSync来获取目录中的所有 Pug 文件。 The synchronous version is used (as opposed to fs.readdir ) because the module.exports function will return before the files are processed.使用同步版本(而不是fs.readdir )因为module.exports函数将在处理文件之前返回。

in 2022 is appeared the Pug plugin for Webpack that compiles Pug to static HTML, extracts CSS and JS from their source files defined directly in Pug. 2022 年出现了 Webpack 的Pug 插件,它将 Pug 编译为 static HTML,从 Pug 中直接定义的源文件中提取 CSS 和 JS。

It is enough to install the pug-plugin only:仅安装pug-plugin就足够了:

npm install pug-plugin --save-dev

webpack.config.js webpack.config.js

const path = require('path');
const PugPlugin = require('pug-plugin');

module.exports = {
  output: {
    path: path.join(__dirname, 'dist/'),
    filename: 'assets/js/[name].[contenthash:8].js'
  },

  entry: {
    // Note: a Pug file is the entry-point for all scripts and styles.
    // All scripts and styles must be specified in Pug.
    // Define Pug files in entry:
    index: './src/views/index.pug', // => dist/index.html
    'navcustom-template': './src/navcustom-template.pug', // => dist/navcustom-template.html
    'customfooter-template': './src/customfooter-template.pug', // => dist/customfooter-template
    // etc ...
  },

  plugins: [
    // enable using Pug files as entry-point
    new PugPlugin({
      extractCss: {
        filename: 'assets/css/[name].[contenthash:8].css' // output filename of CSS files
      },
    })
  ],

  module: {
    rules: [
      {
        test: /\.pug$/,
        loader: PugPlugin.loader, // the Pug loader
      },
      {
        test: /\.(css|sass|scss)$/,
        use: ['css-loader', 'sass-loader']
      },
    ],
  },
};

Of cause, the entry can be dynamically generated like in the answer above.当然,条目可以像上面的答案一样动态生成。

In your Pug file use the source files of styles and scripts via require() :在您的 Pug 文件中,使用 styles 的源文件和通过require()编写的脚本:

html
  head
    //- add source SCSS styles using a path relative to Pug file
    link(href=require('./styles.scss') rel='stylesheet')
  body
    h1 Hello Pug!
    
    //- add source JS/TS scripts
    script(src=require('./main.js'))

Generated HTML:生成 HTML:

<html>
  <head>
    <link href="/assets/css/styles.f57966f4.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello Pug!</h1>
    <script src="/assets/js/main.b855d8f4.js"></script>
  </body>
</html>

Just one Pug plugin replaces the functionality of many plugins and loaders used with Pug:只需一个 Pug 插件就可以取代许多与 Pug 一起使用的插件和加载器的功能:

  • pug-html-loader
  • html-webpack-pug-plugin
  • html-webpack-plugin
  • mini-css-extract-plugin
  • resolve-url-loader
  • svg-url-loader
  • posthtml-inline-svg

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

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