symfony - Webpack 开发服务器监视 Twig

标签 symfony webpack webpack-dev-server

我使用 Symfony 4 和 Symfony Encore 来处理 Assets 和一些有用的功能,例如 HMR。

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

现在我希望能够让 Weback 开发服务器监视 *.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

我想念那里的什么?

最佳答案

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

Webpack 配置解决方案

正如您所说:我见过有关 --watchContentBase 和 contentBase 选项的内容...,这与 encore 无关。它是默认的 webpack 配置,您可以从 webpack doc here 了解更多信息

根据Advanced Webpack Config docs here您可以通过调用 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 docs here您可以实现自定义加载器和插件,如下所示。使用上面提到的插件,我们可以按如下方式实现它:

// 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 - Webpack 开发服务器监视 Twig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196450/

相关文章:

javascript - <script/> 与 <script></script> 使用 webpack 和 Angular

javascript - 使用 webpack-dev-server 进行轮询

javascript - 修复 js "Script error"

web-applications - 基于 LAMP、Symfony2、Backbone 的 Twitter 风格 Web 应用程序 : possible?

Symfony2 : How to login using OAuth (HWIOAuthBundle) + custom roles (by default and loaded from DB)

Symfony Doctrine ManyToMany 添加自定义连接字段

Symfony2 Route 仅在整数时获取参数

angularjs - Angular 2 : How to implement lazy routing with Ahead of Time Compilation?

json - 如何在 webpack-dev-server 中使用 VS Code 调试器(忽略断点)

ruby-on-rails - rails webpack-dev-server "Invalid configuration object"