Skip to content

Wrong path fonts #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dayze opened this issue Jun 16, 2017 · 42 comments
Open

Wrong path fonts #26

dayze opened this issue Jun 16, 2017 · 42 comments

Comments

@dayze
Copy link

dayze commented Jun 16, 2017

When I include semantic or bootstrap in my main.js I end up with a 404 not found error for the fonts

Apparently, the output path of fonts go to the root of my web server like this

http://localhost/build/fonts/icons.woff2

@weaverryan
Copy link
Member

Hey @dayze!

Can you post your webpack.config.js file and also the code for any relevant other files (like main.js)?

@dayze
Copy link
Author

dayze commented Jun 19, 2017

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 

@heitorvrb
Copy link

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

@weaverryan
Copy link
Member

@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:

it('Deploying to a subdirectory is no problem', (done) => {

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.

@heitorvrb
Copy link

It worked. Thanks for the help.

@dayze
Copy link
Author

dayze commented Jun 21, 2017

It worked too, thanks !

@vctls
Copy link

vctls commented Oct 9, 2017

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?

@Lyrkan
Copy link
Collaborator

Lyrkan commented Oct 9, 2017

@vctls Maybe you could use Encore.isProduction() to set the web root dynamically?

Encore.setPublicPath(Encore.isProduction() ? '/build' : '/my-nth-app/web/build');

@vctls
Copy link

vctls commented Oct 9, 2017

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

@scaytrase
Copy link

@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?

@Lyrkan
Copy link
Collaborator

Lyrkan commented Nov 5, 2017

Hi @scaytrase,

I guess you would need to call setPublicPath with a relative path... which isn't allowed right now:

if (publicPath.includes('://') === false && publicPath.indexOf('/') !== 0) {
// technically, not starting with "/" is legal, but not
// what you want in most cases. Let's not let the user make
// a mistake (and we can always change this later).
throw new Error('The value passed to setPublicPath() must start with "/" or be a full URL (http://...)');
}

@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?

@scaytrase
Copy link

scaytrase commented Nov 5, 2017

@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

@kevinpapst
Copy link

kevinpapst commented Jan 30, 2018

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

@weaverryan
Copy link
Member

I’m going to re-open so we can process the new info

@weaverryan weaverryan reopened this Jan 30, 2018
@stoccc
Copy link
Contributor

stoccc commented Feb 1, 2018

@kevinpapst couldn't you do simply

.setPublicPath('build')

or am I missing something?

@scaytrase
Copy link

@stoccc before the patch it was required that public path starts with /

@kevinpapst
Copy link

kevinpapst commented Feb 1, 2018

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

@BerkhanBerkdemir
Copy link

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?

@stoccc
Copy link
Contributor

stoccc commented Feb 2, 2018

@weaverryan it seems that 0.17.2 has not yet been published to npmjs https://www.npmjs.com/package/@symfony/webpack-encore

@kevinpapst
Copy link

@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",

@stoccc
Copy link
Contributor

stoccc commented Feb 2, 2018

@kevinpapst @weaverryan

I am in this scenario:

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 as url(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.

@kevinpapst
Copy link

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?

@scaytrase
Copy link

@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

@weaverryan
Copy link
Member

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.

@MasterB
Copy link

MasterB commented Feb 12, 2018

yes I vote for @stoccc +1

stoccc pushed a commit to stoccc/webpack-encore that referenced this issue Feb 13, 2018
@eberhapa
Copy link

eberhapa commented Mar 8, 2018

Any news on this issue?

@stoccc
Copy link
Contributor

stoccc commented Mar 8, 2018 via email

@idybil
Copy link

idybil commented May 25, 2018

@stoccc solution does not seem to work when using dynamic import (promise).

@stof
Copy link
Member

stof commented May 25, 2018

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

@dspiegel
Copy link

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

@weaverryan
Copy link
Member

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.

@dspiegel
Copy link

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

  1. 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.
  2. Using publicPath as you suggested gets us right back to the original problem of this Issue Wrong path fonts #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

@stof
Copy link
Member

stof commented Jul 17, 2018

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

@dmeziere
Copy link

dmeziere commented Jan 8, 2019

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

@stof
Copy link
Member

stof commented Jan 8, 2019

@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)

@dmeziere
Copy link

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.

@Lyrkan
Copy link
Collaborator

Lyrkan commented Jan 10, 2019

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.

@trsteel88
Copy link

trsteel88 commented Feb 25, 2019

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

@toklok
Copy link

toklok commented Nov 1, 2019

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

@Lyrkan
Copy link
Collaborator

Lyrkan commented Nov 1, 2019

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

@zulus
Copy link

zulus commented Jun 16, 2021

My temporary solution:

  1. .setPublicPath(Encore.isProduction() ? '.' : '/build/admin') - so css will contain font paths relative to css file
  2. .setManifestKeyPrefix('build')
  3. 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.

@carsonbot
Copy link
Collaborator

Thank you for this issue.
There has not been a lot of activity here for a while. Has this been resolved?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests