simperfit/twig-webpack-extension

轻松将webpack入口点注入到twig模板中。

v2.2.0 2020-07-16 11:47 UTC

README

轻松将webpack入口点注入到twig模板中。

此存储库提供了一种将Webpack输出文件与Twig模板引擎轻松结合的Twig扩展。此方法允许使用Webpack生成的哈希动态插入CSS样式表和JavaScript脚本。

同时与 extract-text-webpack-plugin 工作良好

安装

$ composer require fullpipe/twig-webpack-extension

设置Webpack

您需要安装 webpack-manifest-plugin

$ npm install webpack-manifest-plugin --save-dev

# or with Yarn
$ yarn add webpack-manifest-plugin --dev

配置 webpack.config.js

// webpack.config.js

var ManifestPlugin = require('webpack-manifest-plugin');

(...)

module.exports = {

  (...)

  entry: {
    vendor: ["jquery", "lodash"],
    main: './src/main.js'
  },
  output: {
    (...)
    path: './js'
    publicPath: '/',    // required

    (...)
  },
  plugins: [
    new ManifestPlugin(),
    new ExtractTextPlugin({
      filename: './../css/[name].css',
      publicPath: '/'
    }),

  (...)
  ]
}

在Symfony中将Twig扩展注册为服务

# app/config/services.yml

parameters:
    (...)

    webpack.manifest: "%kernel.root_dir%/../web/build/manifest.json" #should be absolute
    webpack.public_path_js: /js/
    webpack.public_path_css: /css/

services:
    (...)

    twig_extension.webpack:
        class: Fullpipe\TwigWebpackExtension\WebpackExtension
        public: false
        arguments:
            - "%webpack.manifest%"
            - "%webpack.public_path_js%"
            - "%webpack.public_path_css%"
        tags:
            - { name: twig.extension }

将入口点注入到您的Twig中

{# app/Resources/views/base.html.twig #}

(...)

<head>
(...)

    {% webpack_entry_css 'main' %}
</head>

<body>
(...)

    {% webpack_entry_js 'vendor' %}
    {% webpack_entry_js 'main' %}
</body>

对输出文件进行哈希处理,避免浏览器缓存

如果您使用 [hash][chunkhash]

// webpack.config.js

(...)

output: {
  (...)

  filename: '[name].[chunkhash].js',
  chunkFilename: '[name].[chunkhash].js'
},
plugins: [
  (...)

  new ExtractTextPlugin({
    filename: './../css/[name].[contenthash].css',
    publicPath: '/'
  }),

  (...)
]

您应该在每次webpack编译后清除twig缓存。因此,对于开发环境,不要使用 [hash][chunkhash]