Webpack开发服务器监视Twig文件

7
我正在使用Symfony 4和Symfony Encore来处理资产,以及一些有用的功能,如HMR。
目前,我可以处理Sass文件、CSS文件、JS等,并且它与HMR很好地配合使用。
现在,我希望能够使Weback dev服务器监视*.twig文件的更改并触发实时重新加载(由于热重新加载不适用于服务器端呈现的模板)。
我看到了关于--watchContentBasecontentBase选项的内容,但在我的情况下它们没有任何作用:
WDS CLI:
./node_modules/.bin/encore dev-server --hot --disable-host-check --watchContentBase --contentBase ./templates/ --reload

webpack.config.js :

const Encore = require('@symfony/webpack-encore');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .autoProvidejQuery()  
    .addPlugin(new MiniCssExtractPlugin('[name].css'))
    .enableSourceMaps(!Encore.isProduction())
    .addLoader({
        test: /\.(sc|sa|c)ss$/,
        use: ['css-hot-loader'].concat(
            MiniCssExtractPlugin.loader,
            {
                loader: 'css-loader'
            },
            {
                loader: 'postcss-loader'
            },
            // {
            //     loader: 'postcss-loader'
            // },
            {
                loader: 'sass-loader'
            }            
        ),
      },)
      .addLoader({
        test: /\.twig$/,
        loader: 'raw-loader'
      },)
    .enableVersioning(Encore.isProduction())
    .addEntry('autocall-main', './assets/js/index.js')
    // .addStyleEntry('autocall-main', ['./assets/scss/index.scss'])
    .splitEntryChunks()
    .enableSingleRuntimeChunk()
;
const config = Encore.getWebpackConfig();

module.exports = config;

我的项目文件/文件夹遵循经典的Symfony 4结构:https://github.com/symfony/demo

那里我错过了什么?


只是好奇,为什么需要使用webpack来监视twig文件?在开发环境中,框架不会自动更新缓存吗? - Arleigh Hix
只是为了在我更改/保存*.twig文件时执行实时重新加载。只是为了节省手动刷新浏览器的时间。 - enguerranws
我可以使用BrowserSync插件来实现,但我想避免使用它,只要WDS能够做到。 - enguerranws
5个回答

4

今天,也就是2020年,我有两个解决方案:

Webpack配置方案

如你所说:“我看到了--watchContentBase和contentBase选项的相关内容...”,这与Encore无关。这是webpack的默认配置,你可以从这里的webpack文档了解更多信息。

根据高级Webpack配置文档,你可以通过调用var config = Encore.getWebpackConfig();来扩展webpack配置。

我已经按照下面的代码实现了这种方法,在我的情况下它运行正常。

// webpack.config.js
var Encore = require('@symfony/webpack-encore');
var path = require('path');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('global', './assets/app.js')

    // ... Your other encore code


    // EXTEND/OVERRIDE THE WEBPACK CONFIG

    const fullConfig = Encore.getWebpackConfig();
    fullConfig.name = 'full';

    // watch options poll is used to reload the site after specific set time
    // polling is useful when running Encore inside a Virtual Machine
    // more: https://webpack.js.org/configuration/watch/
    fullConfig.watchOptions = {
        poll: true,
        ignored: /node_modules/
    };

    fullConfig.devServer = {
        public: 'http://localhost:3000',
        allowedHosts: ['0.0.0.0'],
        // extend folder to watch in a symfony project
        // use of content base
        // customize the paths below as per your needs, for this simple 
        //example i will leave them as they are for now.
        contentBase: [
            path.join(__dirname, 'templates/'), // watch twig templates folder
            path.join(__dirname, 'src/') // watch the src php folder
        ],
        // enable watching them
        watchContentBase: true,
        compress: true,
        open: true,
        disableHostCheck: true,
        progress: true,
        watchOptions: {
            watch: true,
            poll: true
        }
    };


// export it
module.exports = fullConfig;

另一种解决方案

如果你需要一个简单的实现,可以使用:webpack-watch-files-plugin。我更喜欢这个,但可能在你阅读这篇答案时已经被弃用了,但有许多其他具有相同功能的插件可供选择。在Symfony文档中,你可以按照以下方式实现自定义加载器和插件。使用上述提到的插件,我们可以按照以下方式实现:

// webpack.config.js
const WatchExternalFilesPlugin = require('webpack-watch-files-plugin').default;

Encore
    // ...your code

     .addPlugin(new WatchExternalFilesPlugin({
            files: [
                '/templates', // watch files in templates folder
                '/src', // watch files in src folder
                '!../var', // don't watch files in var folder (exclude)
            ],
            verbose: true
        }))

    //...your code
;

加油!愉快编码!


1
使用Symfony 5.4和Encore 1.0.0,您可以在webpack.config.js中手动配置devServer。
...
 .configureDevServerOptions((options) => {
        options.liveReload = true;
        options.hot = true;
        options.watchFiles = [
            './templates/**/*',
            './src/**/*'
        ]
    })
...

2
这个方案是可行的,但不幸的是它会影响到 Encore 条目上的 HMR。只有在将 liveReload 设置为 true 时才能正常工作,但这样会重新加载那些可以通过 HMR 刷新的更改,例如 css、js 等。 - Marfee

0
加载器还需要知道 .twig 文件的位置,在 Symfony 4 中它们位于 /templates 目录中。考虑到默认结构,这应该可以让它为您工作:
  ...
  .addLoader({
    test: /\.twig$/,
    loader: 'raw-loader',
    include: [
      path.resolve(__dirname, "templates")
    ],
  },)
  ...

有趣的是,WebPack Encore 的 Symfony 文档并没有使用 __dirname,而是使用了 ./templates 语法。如果上述方法不起作用,也可以尝试这种方法。 - Siavas
那不起作用,我尝试包括 templates./templates,但当我在 ./templates/base.html.twig 上进行更改时,WDS 没有看到任何更改。 - enguerranws
那么你已经尝试过 path.resolve(__dirname, "templates")path.resolve("./templates") 两种方式了吗? - Siavas
是的,但在这两种情况下,WDS 都看不到 Twig 文件的任何更改。 - enguerranws

0
如果您只需要浏览器同步,您可以创建bs-config.js文件:
module.exports = {
    "files": [
        "templates/**/*.twig",
        "src/**/*.php"
    ],
    "proxy": "https://localhost:8000",
};

然后运行

browser-sync start --config bs-config.js

记得在启动时接受“危险站点”。

0

看起来似乎没有办法做到这一点(请参阅更多信息)。正如提问者所提到的,您可以使用BrowserSync来完成。我喜欢的Symfony设置是有两个终端在运行:

先决条件

安装BrowserSync:

npm install -g browser-sync

第一个终端

https://127.0.0.1:8000/上启动Symfony服务器,并在https://localhost:8010/上构建资源:

symfony server:start -d ; yarn encore dev-server --https --port 8010

第二个终端

每次 Twig 文件更改时,请重新加载您的浏览器对 https://localhost:3000/ 的请求:

browser-sync start --proxy "https://127.0.0.1:8000/" --files "templates"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接