Webpack 开发服务器监视 Twig


我正在使用Symfony

4和Symfony Encore来处理资产,以及一些有用的功能,例如HMR。

目前,我可以处理 Sass 文件、CSS 文件、JS 等,并且可以与 HMR 配合使用。

现在我希望能够让 Weback 开发服务器监视 *.twig 文件的更改并触发实时重新加载(因为热重载不是服务器端渲染模板的选项)。

我已经看到了有关--watchContentBasecontentBase选项的事情,但就我而言,它没有任何作用:

WDS 命令行界面 :

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

我在那里错过了什么?

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

Webpack 配置解决方案

正如你所说:I've seen things about --watchContentBase and contentBase options...,这与安可无关。 它是一个默认的 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
;

干杯。祝您编码愉快!

使用 Symfony 5.4 和 Encore 1.0.0,您可以在 webpack.config 中配置 devServer mannualy.js

...
 .configureDevServerOptions((options) => {
        options.liveReload = true;
        options.hot = true;
        options.watchFiles = [
            './templates/**/*',
            './src/**/*'
        ]
    })
...

加载器还需要知道.twig文件的位置,这些文件在Symfony 4中位于/templates目录中。考虑到默认结构,这应该使其适合您:

  ...
  .addLoader({
    test: /.twig$/,
    loader: 'raw-loader',
    include: [
      path.resolve(__dirname, "templates")
    ],
  },)
  ...

似乎没有办法做到这一点(阅读更多内容)。正如提问者所提到的,您可以使用浏览器同步来做到这一点。我首选的Symfony设置是运行两个终端:

先决条件

安装浏览器同步:

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"

如果你只需要浏览器同步,你可以创建bs-config.js:

module.exports = {
    "files": [
        "templates/**/*.twig",
        "src/**/*.php"
    ],
    "proxy": "https://localhost:8000",
};

然后运行

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

记得在启动时接受"危险站点"

最新更新