Cannot get / with encore dev-server in Symfony - symfony

I would like to point out that I am on a classic Symfony application with the default configuration for Webpack. And that the watch command works very well.
Hello,
When I try to start the Webpack Encore development server, the compilation is done without any problem but when I access the page, I get the error "Cannot GET /". I have no errors in the console
(source: casimages.com)
But interestingly, http://localhost:8000/webpack-dev-server seems to work.
(source: casimages.com)
var Encore = require('#symfony/webpack-encore');
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')ne CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/js/app.js')
//.addEntry('page1', './assets/js/page1.js')
//.addEntry('page2', './assets/js/page2.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
.configureBabel(() => {}, {
useBuiltIns: 'usage',
corejs: 3
})
//.enableSassLoader()
//.enableTypeScriptLoader()
//.enableIntegrityHashes(Encore.isProduction())
.autoProvidejQuery()
.autoProvideVariables({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
})
.enableReactPreset()
;
module.exports = Encore.getWebpackConfig();

I got "Cannot GET /" when trying to reach the server through localhost. Finally Iil I let Symfony open the webpage with the command:
symfony open:local
It opened on https://127.0.0.1:8000

You can check if your files are created in public/build folder. If your files are created completely check if they have appropriate access to read.

Related

Symfony6 - Exception: Could not find the entrypoints file from Webpack

I try to deploy my Symfony application to production.
I already ran the command:
yarn encore prod
I still see the following exception:
An exception has been thrown during the rendering of a template ("Could not find the entrypoints file from Webpack: the file "/home/mobil/public_html/public/build/entrypoints.json" does not exist.").
How can I resolve my issue?
If i'ts a shared hosting, I think i'ts because the setPublicPath configuration.
I had a smillar problem before, the assets works in local but not on server and the solution was to make tow webpack configurations, on for local and the second for prod
https://symfony.com/doc/current/frontend/encore/advanced-config.html#defining-multiple-webpack-configurations
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
.setPublicPath('/build') // local config
.setManifestKeyPrefix('build/')
// ........
})
;
const localConfig = Encore.getWebpackConfig();
localConfig.name = 'localConfig';
// reset Encore to build the second config
Encore.reset();
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
.setPublicPath('/public/build') // for prod on shared hosting
.setManifestKeyPrefix('build/')
// .....
// build the second configuration
const prodConfig = Encore.getWebpackConfig();
// Set a unique name for the config (needed later!)
prodConfig.name = 'prodConfig';
// export the final configuration as an array of multiple configurations
module.exports = [localConfig, prodConfig];
the commands for each config:
./node_modules/.bin/encore dev --config-name localConfig
./node_modules/.bin/encore prod --config-name prodConfig

Symfony and Webpack Image in production

I installed webpack on my symfony project.
I do not understand the system of images and versioning, for example in the site there is a blog, and when I create a new blog post I must necessarily execute npm run dev for after having access to the new image via the folder build.
How to make this happen automatically without having to run the command each time?
const Encore = require('#symfony/webpack-encore');
// 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/')
.copyFiles({
from: './assets/images',
// optional target path, relative to the output dir
to: 'images/[path][name].[ext]',
// if versioning is enabled, add the file hash too
//to: 'images/[path][name].[hash:8].[ext]',
// only copy files matching this pattern
//pattern: /\.(png|jpg|jpeg)$/
})
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
//Main JS
.addEntry('app', './assets/js/app.js')
.addEntry('functions', './assets/js/functions.js')
.addEntry('themepunchrevolution', './assets/rs-plugin/js/jquery.themepunch.revolution.js')
.addEntry('cookieBar', './assets/js/jquery.cookiebar.js')
//Main Css
.addEntry('style', './assets/styles/style.css')
.addEntry('blog', './assets/styles/blog.css')
.addEntry('custom', './assets/styles/custom.css')
.addEntry('extralayers', './assets/styles/extralayers.css')
.addEntry('finaltilesgallery', './assets/styles/finaltilesgallery.css')
.addEntry('flavr', './assets/styles/flavr.min.css')
.addEntry('lightbox2', './assets/styles/lightbox2.css')
.addEntry('owl_video', './assets/styles/owl.video.play.png')
.addEntry('shop', './assets/styles/shop.css')
.addEntry('timeline', './assets/styles/timeline.css')
.addEntry('setting', './assets/rs-plugin/css/settings.css')
.addEntry('setting_ie8', './assets/rs-plugin/css/settings-ie8.css')
.addEntry('vendors', './assets/styles/vendors.unminified.css')
.addEntry('bootstrap_css', './assets/styles/bootstrap.min.css')
//Admin CSS
.addEntry('app_css', './assets/styles/app.css')
.addEntry('admin', './assets/styles/admin.css')
.addEntry('default', './assets/styles/default-css.css')
.addEntry('metisMenu_css', './assets/styles/metisMenu.css')
.addEntry('responsive', './assets/styles/responsive.css')
.addEntry('slicknav_css', './assets/styles/slicknav.min.css')
.addEntry('styles', './assets/styles/styles.css')
.addEntry('typography', './assets/styles/typography.css')
.addEntry('themify', './assets/styles/themify-icons.css')
//preHome
.addEntry('preHome', './assets/styles/style_preHome.css')
.copyFiles([
{from: './node_modules/ckeditor4/', to: 'ckeditor/[path][name].[ext]', pattern: /\.(js|css)$/, includeSubdirectories: false},
{from: './node_modules/ckeditor4/adapters', to: 'ckeditor/adapters/[path][name].[ext]'},
{from: './node_modules/ckeditor4/lang', to: 'ckeditor/lang/[path][name].[ext]'},
{from: './node_modules/ckeditor4/plugins', to: 'ckeditor/plugins/[path][name].[ext]'},
{from: './node_modules/ckeditor4/skins', to: 'ckeditor/skins/[path][name].[ext]'},
{from: './node_modules/ckeditor4/vendor', to: 'ckeditor/vendor/[path][name].[ext]'}
])
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
.configureBabel((config) => {
config.plugins.push('#babel/plugin-proposal-class-properties');
})
// enables #babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
// enables Sass/SCSS support
//.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment if you use React
//.enableReactPreset()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
//.enableVersioning()
// uncomment if you're having problems with a jQuery plugin
.autoProvidejQuery()
;
module.exports = Encore.getWebpackConfig();
You're having this issue because you are storing the user uploaded images under <project dir>/assets. That directory is private by design and not available for a client (browser). Perhaps this is why you added that copyFiles step to your configuration.
Instead of doing that you should store the uploaded images (if you want them available for rendering on a web page) somewhere under <project dir>/public (for example: <project dir>/public/uploads.
Once you do that you'll be able to access them as soon as they are uploaded either specifying the path to them or using the Twig asset function.
Example:
uploaded image is IMG001.jpg
your application stores it under <project dir>/public/uploads/IMG001.jpg
you can access it from your template using {{ asset('uploads/IMG001.jpg') }}
or in plain HTML/JS through src="/uploads/IMG001.jpg"

Workbox wbepack encore dont work (in symfony 4 application)

I apologize if the question already was to find, and that it has an answer, but in research on intenert, I did not find anything which worked.
Here is my problem, I started with workbox, and I tried to integrate it into my Symfony 4 application which still uses webpack, but it does not work properly. So I tried to generate the service worker with the cli, but I still can't get it to work.
My webpack encore configuration:
const Encore = require('#symfony/webpack-encore');
const CompressionPlugin = require('compression-webpack-plugin');
const {GenerateSW, InjectManifest} = require('workbox-webpack-plugin');
const path = require('path')
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.addEntry('app', './assets/js/app.js')
.addEntry('cart', './assets/js/cart.js')
.addEntry('site', './assets/js/site.js')
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.enableSassLoader()
.enableVueLoader(() => {}, { runtimeCompilerBuild: false })
.addLoader({
test: /\.exec\.js$/,
loader: 'script-loader'
})
.autoProvidejQuery()
.autoProvideVariables({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
})
.enableSingleRuntimeChunk()
.addPlugin(new CompressionPlugin())
.addPlugin(new GenerateSW({swDest: 'sw.js'}))
.addPlugin(new InjectManifest({
swSrc: 'sw.js',
exclude: [
/\.map$/,
/manifest$/,
/\.htaccess$/,
/service-worker\.js$/,
/sw\.js$/,
],
}));
module.exports = Encore.getWebpackConfig();
for webpack generate error i have found this: https://github.com/GoogleChrome/workbox/issues/1513 but
After cli generateSW i have this error:
error
Can't find self.__WB_MANIFEST in your SW source.
for wb manifest i have found this:
Webpack workbox Can't find self.__WB_MANIFEST in your SW source but doesn't work for me
I think the problem comes from the url generated by webpack and i have found this:
Can't install service worker of workbox-webpack-plugin in root url for React app, it's installing at localhost:8080/dist
But I don't see how it helps me in my configuration.
I have tried with path.resolve (because on forum i have seen work), but don't work for me, i get this error:
Can't find self.__WB_MANIFEST in your SW source.
Thank for your help !
import { precacheAndRoute } from 'workbox-precaching';
// Your other import statements go here.
precacheAndRoute(self.__WB_MANIFEST);
On your sw.js

Webpack dev server watches Twig

I'm using Symfony 4 with Symfony Encore to handle assets, and some useful features, such as HMR.
Currently, I can handle Sass files, CSS files, JS, etc, and it works fine with HMR.
Now I would like to be able to make Weback dev server watch *.twig files for changes and trigger a live reload (as hot reload wouldn't be an option for server-side rendered templates).
I've seen things about --watchContentBase and contentBase options, but it doesn't do anything in my case:
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;
My project files / folders follows the classic Symfony 4 structure: https://github.com/symfony/demo
What do I miss there?
Today, the year 2020, i have two solutions:
Webpack config solution
As you had said: I've seen things about --watchContentBase and contentBase options..., this has nothing to do with encore. Its a default webpack configurations and you can learn more from webpack doc here
According to Advanced Webpack Config docs here you can extend webpack configs by calling var config = Encore.getWebpackConfig();
I have implemented as shown in the code below. For my case its working fine.
// 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;
Another solution
If you need a simple implementation you can use: webpack-watch-files-plugin. I prefer this, by the time you are reading this answer it might be abandoned but there many others with same functionality. In Symfony docs here you can implement Custom Loaders & Plugins as below. Using the above mentioned plugin we can implent it as follow:
// 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
;
Cheers. Happy coding!
With Symfony 5.4 and Encore 1.0.0 you can configure devServer mannualy in webpack.config.js
...
.configureDevServerOptions((options) => {
options.liveReload = true;
options.hot = true;
options.watchFiles = [
'./templates/**/*',
'./src/**/*'
]
})
...
The loader needs to know also the location of the .twig files, which in Symfony 4 are in /templates directory. Considering the default structure, this should make it work for you:
...
.addLoader({
test: /\.twig$/,
loader: 'raw-loader',
include: [
path.resolve(__dirname, "templates")
],
},)
...
It seems that there is no way to do that (read more on this). As the questioner mentions you can do it with BrowserSync. My preferred Symfony setup is to have two terminals running:
Prerequisites
Install BrowserSync:
npm install -g browser-sync
First terminal
Start the Symfony server on https://127.0.0.1:8000/ and build the assets on https://localhost:8010/:
symfony server:start -d ; yarn encore dev-server --https --port 8010
Second terminal
Reload your browser's request for https://localhost:3000/ every time a Twig file gets changed:
browser-sync start --proxy "https://127.0.0.1:8000/" --files "templates"
If you need only browser-sync you can create bs-config.js:
module.exports = {
"files": [
"templates/**/*.twig",
"src/**/*.php"
],
"proxy": "https://localhost:8000",
};
and then run
browser-sync start --config bs-config.js
remember to accept the "dangerous site" at startup

Symfony Encore/Webpack never completes

Anytime I try to run encore, it doesn't complete and hangs at...
$ /vagrant/app/node_modules/.bin/encore dev
Running webpack ...
I've removed node_modules and re-installed numerous times following the Symfony documentation. Tried using only npm and also tried only using yarn. Any suggestions would be much appreciated. I've included package.json and webpack.config.js, if there is anything else needed to help troubleshoot, please let me know.
package.json
{
"devDependencies": {
"#symfony/webpack-encore": "^0.20.1",
"node-sass": "^4.9.0",
"sass-loader": "^7.0.3"
}
}
webpack.config.js
var Encore = require('#symfony/webpack-encore');
Encore
// the project directory where compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/app/build')
.setManifestKeyPrefix('build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
// uncomment if you use Sass/SCSS files
.enableSassLoader()
// uncomment to create hashed filenames (e.g. app.abc123.css)
// .enableVersioning(Encore.isProduction())
// uncomment to define the assets of the project
// .addEntry('js/app', './assets/js/app.js')
.addStyleEntry('css/style', './assets/sass/style.scss')
// .addStyleEntry('css/print', './assets/sass/print.scss')
// uncomment for legacy applications that require $/jQuery as a global variable
// .autoProvidejQuery()
;
module.exports = Encore.getWebpackConfig();
I figured out the issue. I had to disable the resolveUrlLoader in my sass loader options.
.enableSassLoader(function(options) {}, {
resolveUrlLoader: false
})

Resources