symfony / webpack-encore

A simple but powerful API for processing & compiling assets built around Webpack
https://symfony.com/doc/current/frontend.html
MIT License
2.23k stars 199 forks source link

Setting dev server host to custom local domain resolves to 127.0.0.1 #951

Open leevigraham opened 3 years ago

leevigraham commented 3 years ago

webpack-encore: 1.1.2

When setting the host to craft-boilerplate.localhost the webpack-dev-server resolves it to 127.0.0.1 and starts the dev-server:

image

This behaviour can be triggered using either the host parameter in the dev-server options or via the --host flag.

I wanted the dev server to run on a custom host craft-boilerplate.localhost so I could use the same locally generated SSL certificate for the project.

Additionally the manifest.json produced still points to https://localhost:8080:

{
  "theme/dist/app.css": "https://localhost:8080/theme/dist/app.css",
  "theme/dist/app.js": "https://localhost:8080/theme/dist/app.js",
  "theme/dist/runtime.js": "https://localhost:8080/theme/dist/runtime.js",
  "theme/dist/vendors-node_modules_webpack-dev-server_client_default_index_js_https_craft-boilerplate_local-4ef0ad.js": "https://localhost:8080/theme/dist/vendors-node_modules_webpack-dev-server_client_default_index_js_https_craft-boilerplate_local-4ef0ad.js",
  "theme/dist/images/pattern.png": "https://localhost:8080/theme/dist/images/pattern.c1e510cc.png",
  "theme/dist/images/logo.svg": "https://localhost:8080/theme/dist/images/logo.8c23ac65.svg"
}

Dev server config:

  .configureDevServerOptions(options => {
    options = {
      ...options,
      firewall: false,
      https: {
        key:  fs.readFileSync(process.env.SSL_KEY),
        cert:  fs.readFileSync(process.env.SSL_CERT),
      },
      // liveReload and static are used to reload the whole page
      // when anything in templates changes
      liveReload: true,
      static: {
        directory: path.resolve(__dirname, 'templates'),
        publicPath: '/',
        serveIndex: true,
        watch: true,
      },
      host: 'craft-boilerplate.localhost',
      port: '3000'
    })

bash command:

encore dev-server --host craft-boilerplate.localhost

Full webpack config:
```js require('dotenv-flow').config(); const path = require('path'); const fs = require('fs'); 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/theme/dist/') // public path used by the web server to access the output path .setPublicPath('/theme/dist') // only needed for CDN's or sub-directory deploy //.setManifestKeyPrefix('build/') /* * ENTRY CONFIG * * Add 1 entry for each "page" of your app * (including one that's included on every page - e.g. "app") * * 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. */ .addEntry('app', './public/theme/src/scripts/index.js') //.addEntry('page1', './assets/page1.js') //.addEntry('page2', './assets/page2.js') // 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()) // enables post-css-loader .enablePostCssLoader() // enables @babel/preset-env polyfills .configureBabelPresetEnv((config) => { config.useBuiltIns = 'usage'; config.corejs = 3; }) .copyFiles({ from: './public/theme/src/images', to: 'images/[path][name].[hash:8].[ext]', }) .configureDevServerOptions(options => { options = { ...options, firewall: false, https: { key: fs.readFileSync(process.env.SSL_KEY), cert: fs.readFileSync(process.env.SSL_CERT), }, // liveReload and static are used to reload the whole page // when anything in templates changes liveReload: true, static: { directory: path.resolve(__dirname, 'templates'), publicPath: '/', serveIndex: true, watch: true, } } return options; }) ; let config = Encore.getWebpackConfig(); module.exports = config; ```
leevigraham commented 3 years ago

Update…

I can change the host the dev-server is running on using the public options: https://webpack.js.org/configuration/dev-server/#devserverpublic but I don't think that is the right approach (and doesn't affect the manifest.json):

image

image

natewiebe13 commented 3 years ago

I just ran into a similar issue which I believe was introduced by https://github.com/symfony/webpack-encore/commit/4178f64161b5acaec36f7f9a39c0de57adc10353

I use a remote server that runs Encore, but after a discussion with the webpack-dev-server folks, the client.host setting is meant for when proxying, otherwise host should be set.

The command we use is:

yarn encore dev-server --port=8080 --public="https://mydevserver.com:8080"

and my dev server config looks like:

.configureDevServerOptions((options) => {
    options.host     = '0.0.0.0';
    options.firewall = false;

    delete options.client;
})

options.host binds to 0.0.0.0 and options.client needs to be removed as it breaks the websocket connection. In the command, the public argument is used for the static urls that are used in the twig templates.

yakobe commented 3 years ago

It seems the --public option no longer exists? The api for webpack is pretty unstable at the moment 😅.

I also need to be able to set a url, but i haven't found a way yet that will be reflected in the manifest and entrypoint files.

yakobe commented 3 years ago

I have been using the beta version of webpack-dev-server for a while so that i can continue to use --public but this no longer works now that encore requires 4.0.0 stable.

@weaverryan any ideas how to use hosts other than localhost? The documentation here no longer applies: https://symfony.com/doc/current/frontend/encore/virtual-machine.html#configure-the-public-path and i have juggled several ideas without success.

Any help would be much appreciated. I can help update the docs if i can get it to work 😜.

natewiebe13 commented 3 years ago

@yakobe for v4 stable, I've made the following changes to webpack.config.js

.setPublicPath((process.env.BASE_URL || '') + '/build')
// only needed for CDN's or sub-directory deploy
.setManifestKeyPrefix('build/')
.configureDevServerOptions((options) => {
    options.allowedHosts = 'all';
    options.host         = '0.0.0.0';
    options.client       = {
        webSocketURL: 'auto://0.0.0.0:8080/ws'
    };
})

Using this, I've been able to set the base URI as an env variable and it seems to do the trick. The reasoning behind this, is supplying the public path this way will be done for all of Webpack, not just the dev server, which is more ideal.

See: https://github.com/symfony/webpack-encore/issues/1014

@weaverryan https://symfony.com/doc/current/frontend/encore/virtual-machine.html#configure-the-public-path should be updated if the process hasn't been started yet.

StudioMaX commented 3 years ago

I am using WSL2 to execute the webpack-dev-server, which has an IP, for example, 172.27.10.20. And with standard settings of Hyper-V, this IP is dynamic, that is, it changes every time the WSL2 is started.

With webpack-dev-server 4.0.0 I can use the following config (plain webpack.config.js):

    devServer: {
        host: "local-ip",
        port: 1234,
        client: {
            webSocketURL: {
                hostname: "wsl.internal",
            },
        },
        ...
    }

Thus, the assets will be available in the browser under https://wsl.internal:1234/.... It would be great if support for the new local-ip/local-ipv4/local-ipv6 constants will be added as a value for host (https://webpack.js.org/configuration/dev-server/#local-ip). Even better if local-ip will be automatically converted to a real local IP address in manifest.json.

yakobe commented 3 years ago

@natewiebe13 Thanks for that! It works, so we can upgrade and move forward. It would be cool if we could still do it over the CLI (like with --public) because it's a bit easier to manage. But this really helps.

xiaoyouyu commented 2 years ago

Why can't set host to hostname now?

MetalArend commented 1 year ago

@natewiebe13 Thanks for that! It works, so we can upgrade and move forward. It would be cool if we could still do it over the CLI (like with --public) because it's a bit easier to manage. But this really helps.

Ended up using this information to be able to run the webpack devserver in a nodejs Docker container behind Traefik: npm run dev-server -- --public yourhost:yourport --host 0.0.0.0 --port yourport --allowed-hosts all

carsonbot commented 2 weeks ago

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