Comments (41)
@heitorvrb Ah, thanks for the extra info! If you're deployed under a subdirectory, that should be reflected in your setPublicPath
:
// this is your *true* public path
.setPublicPath('/mySymfonyApp/build')
// this is now needed so that your manifest.json keys are still `build/foo.js`
// i.e. you won't need to change anything in your Symfony app
config.setManifestKeyPrefix('build')
You can see an example of this in the tests as well:
webpack-encore/test/functional.js
Line 180 in db980b4
Webpack must be aware of the true public path, because if you use "code splitting", then webpack itself will make AJAX requests for assets (so it needs to know the real path). That's why the config lives in webpack.config.js
, instead of allowing your app (i.e. Symfony) to "fix" the subdirectory.
Let me know if that helps! I'll open an issue on the docs about this.
from webpack-encore.
I am in this scenario:
- my symfony app is deployed in production under a subdirectory, e.g. www.myhost.com/apps/mySymfonyApp
- the same app is under www.myhost.com/some/development/path/mySymfonyApp for development purposes and under www.myhost.com/some/demo/path/mySymfonyApp for demo purposes
- if possibile, I don't want to care in my config what is the path where the app is deployed
I have deleted these two lines of code in version 0.17.2 (they add a traling slash if it is not present), so that I can have a public path defined as ''
(otherwise it is transformed to '/'
).
With this configuration in webpack.config.js
.setOutputPath('public/build/')
.setPublicPath('')
.setManifestKeyPrefix('build/')
all works correctly:
-
I can access assets from twig with
{{ asset('build/app.js') }}
-
And if some scss file (like in Bootstrap) uses some other file (like glyphicons fonts) they are referenced properly. For example
glyphicons-halflings-regular.eot
is referenced asurl(fonts/glyphicons-halflings-regular.f4769f9b.eot)
in compiled css.
I am wondering: is this solution acceptable or are there some other consequences/scenarios which I can't figure out (I'm new to encore/webpack and nodejs..)?
If it is acceptable, we could test if publicPath
is not empty before adding the trailing slash.
from webpack-encore.
What if my web root changes depending to the environment I'm deploying to?
On my local development environment, the web root will be /my-nth-app/web/build
whereas on the production server, it will just be /build
.
What would be the recommended way to make this dynamic, or at least, configurable?
from webpack-encore.
@kevinpapst couldn't you do simply
.setPublicPath('build')
or am I missing something?
from webpack-encore.
@Lyrkan commenting this error and passing relative path makes internal CSS files to import like
basedir/build/build/fonts/fontawesome.ttf
The build
doubles since CSS file is placed inside the build
and it calls relative build/fonts/.../
So we really need the possibility to rewrite the paths
from webpack-encore.
@stoccc and everyone who wants to test. you can change your package.json
to
"@symfony/webpack-encore": "git://github.com/symfony/webpack-encore.git#0.17.2",
from webpack-encore.
@toklok Even without CI/CD I wouldn't recommend commiting them. Building them locally before a deployment, or even directly on the server (which is not really a good thing either) are probably better solutions.
from webpack-encore.
@vctls Maybe you could use Encore.isProduction()
to set the web root dynamically?
Encore.setPublicPath(Encore.isProduction() ? '/build' : '/my-nth-app/web/build');
from webpack-encore.
@weaverryan it seems that 0.17.2 has not yet been published to npmjs https://www.npmjs.com/package/@symfony/webpack-encore
from webpack-encore.
I use sub directories for sites while in dev and it was a bit of a pain setting a publicPath. Especially when co-workers had different sub directory structures.
I wrote some code to automatically determine the public directory across all projects within the webpack config.
webpack.config.js
var Encore = require('@symfony/webpack-encore');
var publicPath = '/build';
if (!Encore.isProduction()) {
require('dotenv').config({
path: './.webpack.env',
});
if ('undefined' !== typeof process.env.ENCORE_PUBLIC_PATH) {
publicPath = process.env.ENCORE_PUBLIC_PATH;
} else {
const guessFromPaths = [
'/usr/local/var/www/htdocs',
'/usr/local/var/www',
process.env.HOME + '/Sites',
];
for (var i = 0; i < guessFromPaths.length; i++) {
var path = guessFromPaths[i];
if (0 === __dirname.indexOf(path)) {
path = __dirname.split(path);
publicPath = path[1] + '/public/build';
break;
}
}
}
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath(publicPath)
// only needed for CDN's or sub-directory deploy
.setManifestKeyPrefix('build/')
...
You will need to install dotenv from yarn for this to work.
In the above code we are just giving it an array of potential web root directories to look for. This is a list that a few different co-workers are using.
As soon as the loop find a value that matches the __dirname variable, it will take that value and append /public/build to the value.
e.g. if your build files are located in /usr/local/var/www/htdocs/clientXYZ/project123/public/build it will make the public path /clientXYZ/project123/public/build
We also have a .encore.env.dist where you can set a value for ENCORE_PUBLIC_PATH
from webpack-encore.
I tried many combinations, but missed that the slash is automatically added on an empty string. I can confirm that your solution works @stoccc. Thanks, good spotting!
The manifest.json is generated correctly and the assets have a proper relative URL. Versioning works and I can use the JsonManifestVersionStrategy. @weaverryan any thoughts on an empty publicPath?
from webpack-encore.
Awesome! Then we should create a PR! I need to do some git blame to make sure I remember why that trailing slash is so important usually. However, based on why I’ve heard, we may be able to skip that trailing slash of the publicPath argument does not have the starting slash. Basically, you’d opt in to absolute paths or relative.
So yea - can someone create a PR? We have a great test suite in functional.js - it would be pretty easy to setup a seriously solid test to make sure the edge cases all work.
from webpack-encore.
Hey @dayze!
Can you post your webpack.config.js file and also the code for any relevant other files (like main.js)?
from webpack-encore.
Hi,
webpack.config.js
var Encore = require('@symfony/webpack-encore');
Encore
// directory where should all compiled assets will be stored
.setOutputPath('web/build/')
// what's the public path to this directory (relative to your project's document root dir)
.setPublicPath('/build')
// empty the outputPath dir before each build
.cleanupOutputBeforeBuild()
// will output as web/build/app.js
.addEntry('app', './assets/js/main.js')
// will output as web/build/global.css
.addStyleEntry('global', './assets/css/global.scss')
// allow sass/scss files to be processed
.enableSassLoader()
// allows legacy applications to use $/jQuery as a global variable
.autoProvidejQuery()
.enableSourceMaps(!Encore.isProduction())
// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()
;
var webpackConfig = Encore.getWebpackConfig();
webpackConfig.module.rules.push({
test: /\.vue$/,
loader: 'vue-loader'
});
webpackConfig.module.rules.push({
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
});
// export the final configuration
module.exports = webpackConfig;
main.js
import Vue from 'vue/dist/vue'
import App from './app.vue'
require('semantic-ui/dist/semantic.min.css')
Errors
GET http://localhost/build/fonts/icons.woff2
GET http://localhost/build/fonts/icons.woff
GET http://localhost/build/fonts/icons.ttf
from webpack-encore.
Same issue here, with similar configuration. The situation seems to be that my app doesn't run on a ground-level domain, but on a alias on apache:
Alias /mySymfonyApp /var/www/html/mySymfonyApp/web
So webpack is trying to create the src: url()
paths with /build/fonts/myFont.eot
, when it should be /mySymfonyApp/build/fonts/myFont.eot
.
webpack.config.js:
var Encore = require('@symfony/webpack-encore');
Encore
.setOutputPath('web/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.addEntry('app', './app/Resources/js/app.js')
.addStyleEntry('global', './app/Resources/scss/global.scss')
.enableSassLoader({
resolve_url_loader: false
})
.autoProvidejQuery()
.enableSourceMaps(!Encore.isProduction())
// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()
;
// export the final configuration
module.exports = Encore.getWebpackConfig();
global.scss:
@charset 'utf-8';
$fi-path: "~foundation-icon-fonts/";
@import '~foundation-sites/assets/foundation';
@import '~foundation-icon-fonts/foundation-icons';
Resulting global.css:
// [...]
@font-face {
font-family: "foundation-icons";
src: url(/build/fonts/foundation-icons.eot);
src: url(/build/fonts/foundation-icons.eot?#iefix) format("embedded-opentype"), url(/build/fonts/foundation-icons.woff) format("woff"), url(/build/fonts/foundation-icons.ttf) format("truetype"), url(/build/images/foundation-icons.svg#fontcustom) format("svg");
font-weight: normal;
font-style: normal; }
// [...]
localhost/build/fonts/foundation-icons.ttf
obviously 404s, the correct path would be localhost/mySymfonyApp/build/fonts/foundation-icons.ttf
from webpack-encore.
It worked. Thanks for the help.
from webpack-encore.
It worked too, thanks !
from webpack-encore.
@Lyrkan I will do that, thank you :)
It feels a little hacky, though. I wonder if there's any way of detecting the web root.
from webpack-encore.
@Lyrkan what if I use artifact-based deploying and the builder do not really know where the artifact would be deployed to?
Is it possible just make path relative to manifest?
from webpack-encore.
Hi @scaytrase,
I guess you would need to call setPublicPath
with a relative path... which isn't allowed right now:
webpack-encore/lib/WebpackConfig.js
Lines 122 to 127 in 7997206
@andyexeter had a similar issue here: #88 (comment)
We could probably add an allowRelativePath
parameter to that method in order to disable that check... what do you think @weaverryan?
from webpack-encore.
@weaverryan thanks for the release 0.17.2. I tested it and it kind of works. But as you already expected, its not a solution that solves all problems. By setting .setPublicPath('./')
to a relative value and .setManifestKeyPrefix('build/')
the linked resources in generated files (like url to fonts in css files) are relative, so first goal achieved.
But the next problem is that these relative paths become also part of the manifest.json:
"build/app.css": "./app.css",
"build/app.js": "./app.js",
"build/fonts/fontawesome-webfont.eot": "./fonts/fontawesome-webfont.674f50d2.eot",
That now collides when using the JsonManifestVersionStrategy
as the path to my assets are wrong:
assets:
json_manifest_path: '%kernel.project_dir%/public/build/manifest.json'
and
<script src="{{ asset('build/app.js') }}"></script>
results in
<link rel="stylesheet" href="/./app.css">
We could now disable the JsonManifestVersionStrategy
, even though we would loose the option for .enableVersioning(Encore.isProduction())
. But even with deactivated versioning, my required assets like images will still have a hashed filename, e.g.require('../images/default_avatar.png');
will result in a file called public/build/images/default_avatar.fc197350.png
and therefor I can't use {{ asset('build/images/default_avatar.png') }}
for it.
All in all your fix might solve some problems, but I guess it doesn't help with the usecase of generating assets in a way that they work both on root level and in a subdirectory in combination with SF4 and Twig. But I am new to encore and webpack, so I might miss something, any help would be great.
from webpack-encore.
I’m going to re-open so we can process the new info
from webpack-encore.
@stoccc before the patch it was required that public path starts with /
from webpack-encore.
@stoccc No, the public path is not only used for building the manifest.json, it is used to reference assets like font urls within scss files. So a generated css file, lets say build/app.css
, would reference a font with url(build/fonts/myfont)
and that would result in a 404. Its relative location to the css file is fonts/myfont
as @scaytrase wrote above.
My usecase could be solved, if we would be able to set the publicPath for compile time independent from the publicPath prefix used in the manifest.json. But I couldn't find a setting in webpack config for that.
from webpack-encore.
I had same problem. and I solve like this
I have public/build
folder. This folder for JS/CSS. I just add this line from
.setPublicPath('/build/')
to
.setPublicPath('/public/build/')
Actually, I'm not sure. Is it secure way to use?
from webpack-encore.
@weaverryan I can confirm that @stoccc way worked to mee to with latest version installed from github (like @kevinpapst referenced). Commenting out these two lines makes base directory changing work without touching any code or configs
from webpack-encore.
yes I vote for @stoccc +1
from webpack-encore.
Any news on this issue?
from webpack-encore.
from webpack-encore.
@stoccc solution does not seem to work when using dynamic import (promise).
from webpack-encore.
there are multiple cases not working:
- dynamic JS imports
- images required from JS to get their path to insert in the DOM
In both cases, webpack needs to know the path to put them in the DOM, and a relative path here would be relative to the document (so being on /
or on /blog/2018/hello.html
requires a different relative path).
from webpack-encore.
Two cents:
I've been battling this for days now. IMHO Community Focus for Symfony and other packages always seem to be on a single app running on a single web server under the root folder. In reality we run many separate apps on a single web server with each app running under different sub folder path. Don't get me started about issues trying to run behind a corporate firewall.
i.e.
http://example.com/app1 -> /apps/app1/public
http://example.com/app2 -> /apps/app2/public
My Current Issue:
My main issue was the addition of double build "/build/build/" for font-awesome woff2 and woff url links inside my layout.css file.This occurred when using public path set to "build/" and no prefix. Just FYI, the warning by setPublicPath about not starting with '/' is very annoying. My app won't even work if it starts with '/', except for server:run, but I'm not using that in production.
Currently using Symfony 4.1 with
"@symfony/webpack-encore": "^0.19.0",
"bootstrap": "^4.1.1",
"font-awesome": "^4.7.0",
My Solution
I seem to have found partial solution that works as long as I don't use enableVersioning. Here are relevant Encore settings that work for both http://localhost:8000 and http://example.com/app1/ URL's.
.setOutputPath('public/build/')
.setPublicPath('../build')
.setManifestKeyPrefix('../build')
//.enableVersioning(Encore.isProduction())
Symfony Framework issue:
Did not add framework.assets.json_manifest_path but I am using framework.assets.version to set unique version number to asset. For some reason Symfony Framework ignores the manifest.json and marks asset using unversioned name. I was able to use Symfony versioning for now.
Using PublicPath = '../build' and json_manifest_path, this is sample of what occurred
imanifest.json =
"../build/layout.css": "../build/layout.a0beb1a4.css",
"../build/layout.js": "../build/layout.3bc13eb7.js",
Web page =
<link rel="stylesheet" href="/app1/build/layout.css">
<script src="/app1/build/layout.js"></script>
Settings:
framework. assets.json_manifest_path: '%kernel.project_dir%/public/build/manifest.json'
Not sure if I should create issue in Framework for this until Encore issues are resoled (if possible).
Thanks, Dave
from webpack-encore.
Hey Dave!
There may be a misunderstanding about the public path setting. Or maybe the docs are indeed over simplifying things :).
If your app1 will ultimately be accessible as example.com/app1, then your public path should be /app1. Webpack / Encore doesn’t care that your app is in s subdirectory or even know this (unlike Symfony, which can detect it). The publicPath is much simpler: it’s used as the prefix to your assets when they are built. If your app will ultimately reside under /app1, then that’s your publicPath (plus any /build directory where you’re putting things). The warning is meant to be annoying - bad/strange things happen (at least currently) when you try to make this path relative.
So, that would be my recommendation: make your publicPath /app1/build because that is the final public path to our assets - it doesn’t matter what the underlying file structure looks like :).
Let me know how it goes. We cover the subdirectory topic in the FAQ, but I have noticed smart people getting confused by this recently.
from webpack-encore.
@weaverryan sorry I did not see your reply until today. I forgot to add myself to watch.
Thanks for feedback.
Your recommendation to define publicPath, does work when using Apache web server, however
are still issues/conundrums.
- Currently I maintain the base starter project for other developers inside our company. The webpack config and package setup are defined inside this project/bundle. Since I do not know the final application name or location of application, I rely on relative functionality that has worked in previous Symfony versions. The developer decides the name and location where application is deployed, but I don't think they should modify or change base bundle located inside vendor folder.
- Using publicPath as you suggested gets us right back to the original problem of this Issue #26 "404 not found" for all fonts when trying to test using server:run command. However it does work using Apache.
Here is example showing 404 error when using server:run:
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52554 [200]: /about/
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52556 [200]: /build/layout.css
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52558 [200]: /build/about.css
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52560 [200]: /build/manifest.js
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52562 [200]: /build/layout.js
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52564 [200]: /bundles/fosjsrouting/js/router.js
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52568 [200]: /build/about.js
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52566 [200]: /js/routing?callback=fos.Router.setData
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52570 [404]: /navigator/build/fonts/fontawesome-webfont.af7ae505.woff2
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52588 [200]: /_wdt/ea1879
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52590 [404]: /navigator/build/fonts/fontawesome-webfont.fee66e71.woff
[Mon Jul 16 14:40:31 2018] 127.0.0.1:52592 [404]: /navigator/build/fonts/fontawesome-webfont.b06871f2.ttf
Here are project settings I tested by changing project
vendor/group/web_app_bundle//Resources/config/webpack.config.js where "navigator" is the application name (example.com/navigator/).
.setOutputPath('public/build/') .setPublicPath('/navigator/build') .setManifestKeyPrefix('navigator/build')
Any ideas or suggestion how to resolve this would be greatly appreciated.
Thanks, Dave
from webpack-encore.
@dspiegel relative public path can work on the Symfony side, because it can auto-detect the path needed to access the app web root from the server web root. But webpack itself needs to be able to load more files from some files it generates, and it cannot auto-detect the webserver configuration at build time.
And the 404 you faced when using server:run
while using /navigator/build
as your public path is logical, as your public path does not include /navigator
in this case. You would have to make this config dependant on the env running it.
from webpack-encore.
I am just desperated that SF team opted for a JavaScript solution to handle the assets. Nothing works no more with this technology. And there is no way to maintain it without absorbing a whole lot knowledge about JavaScript. I just hate this "language". When it's not the sass-loader that falls down, you discover that it just can't handle multiple environments. I think I will end with totally uninstalling webpack and find a working PHP solution, that can be configured, fixed, and adapted if necessary to anyone's needs. Frustrated. Why don't you use a stable language, something defined, something that runs the same on any environment. Something that works like any other language. Or maybe it's time to stop working with SF, but it is so sad ...
from webpack-encore.
@dmeziere you are still free to build your assets the way you want, and reference them with the asset()
function in your Twig template. The Asset component has no requirement on webpack-encore.
Modern tooling regarding building frontend code is all written in JS. And we decided to recommend webpack (with this wrapper around its config to simplify it for the use cases we see). But it is not mandatory to use it with Symfony at all.
And regarding using a pure PHP solution, there is no PHP-based tooling implementing a module bundler for JS (JS developers build their tooling in the language they know: JS). And the Symfony core team has no interest into porting Webpack and its whole ecosystem to PHP (that would make no sense, and would require many full-time developers to catch up with the whole webpack community).
You can still do that yourselves if you want to use JS modules. And if you want to keep writing JS in the old way and only concatenate the files together in your final bundle, it is easy to implement that in any language (including a simple Bash command: cat assets/js/*.js > web/build/js/app.js
)
from webpack-encore.
So, I finally found the problem. It was an impact on fos_js_routing. But the frustration of loosing days on this point didn't help me to see things clearly. Finally the solution provided by @Lyrkan was the key as I also use aliases on my dev server, but not on my production server. But if you, falling on this ticket, are using fos_js_routing; be aware that the generated js/json file is not called anymore. It is integrated by webpack encore to the main JS file (what makes sense, after all). So you must make it "prod friendly" before calling yarn encore production. And you no longer need to dump the routes in your deployment script, this will be useless. Finally, I don't like the fact that I must compile and commit my production assets to my repo before a deployment, but it is way better than being forced to install node on the production server, downloading all the node_modules, etc.
from webpack-encore.
I don't like the fact that I must compile and commit my production assets to my repo before a deployment
@dmeziere Building the assets before a deployment is a good thing, but I'm not sure why you'd have to commit these files.
By the way, if you have more than two public paths to manage you can do something like this:
Encore.setPublicPath(process.env.ENCORE_PUBLIC_PATH || '/build');
Then simply set the ENCORE_PUBLIC_PATH
environment variable before calling Encore.
from webpack-encore.
@dmeziere Building the assets before a deployment is a good thing, but I'm not sure why you'd have to commit these files.
Some of us don't use CI/CD builds and must commit these files.
from webpack-encore.
My temporary solution:
.setPublicPath(Encore.isProduction() ? '.' : '/build/admin')
- so css will contain font paths relative to css file- .setManifestKeyPrefix('build')
- After
module.exports = Encore.getWebpackConfig()
add
if (Encore.isProduction()) {
module.exports.plugins[2].options.publicPath = 'bundles/w3desadmin/build/' // [2] is WebpackManifestPlugin position
}
Now after yarn run build I have css with relative paths, and asset() function works fine. Unfortunately entrypoints.json have wrong paths, I cannot override it in similar way because AssetsWebpackPlugin calls webpackConfig.getRealPublicPath() directly.
from webpack-encore.
Related Issues (20)
- webpack-encore not working correctly in a live server
- how to add plugins HOT 1
- HMR not working with custom domain HOT 1
- How can I transpileDependencies when using webpack encore
- Debugging hanging CSSMinimizerPlugin
- Module build failed: Module not found: "@symfony/stimulus-bundle" HOT 2
- Allow to pass options to babel react preset
- Twig file changes are not working with "watch" or "dev-server" HOT 1
- Getting an error for assets compilation with webpack-encore.
- ReferenceError: __VUE_PROD_DEVTOOLS__ is not defined HOT 2
- Disabling notifications on windows breaks --watch flag HOT 1
- Warning on sass-loader 14 HOT 1
- Svelte loader Module not found
- Two different builds for two versions of Vue.js app HOT 3
- Warning for postcss-loader v8.1.0 to be too new HOT 3
- PrettyError not supported anymore results in an error HOT 3
- Fully support less-loader ^12 HOT 1
- Enhance assets versionning HOT 12
- Support eslint 9 HOT 1
- Disable dev-server reload for PHP files?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from webpack-encore.