Skip to content
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

How to add alias and externals in encore #200

Closed
tristanbes opened this issue Nov 12, 2017 · 19 comments · Fixed by #217
Closed

How to add alias and externals in encore #200

tristanbes opened this issue Nov 12, 2017 · 19 comments · Fixed by #217

Comments

@tristanbes
Copy link

tristanbes commented Nov 12, 2017

Hello,

Since webpack is obscure to me, I'm giving encore a chance but i'm strugling with how to add an alias and externals entries

    resolve: {
      extensions: ['.js', '.json', '.vue'],
      alias: {
        Translator: 'node_modules/bazinga-translator/js',
      },
    },
    externals: {
      vue: 'Vue',
      vuex: 'Vuex',
      google: 'google',
      leaflet: 'L',
      markerclustererplus: 'MarkerClusterer',
      routing: 'Routing',
      app: 'app',
      translator: 'Translator',
    },

I tried ctrl+f in encore API but didn't found it :(

@tristanbes
Copy link
Author

tristanbes commented Nov 12, 2017

I tried

.autoProvideVariables({
  'window.Routing': 'routing',
})

But babel is creaming at me because it doesn't find the depandancies
import Routing from 'routing'; (which is the js exposed from https://github.com/FriendsOfSymfony/FOSJsRoutingBundle)

My previous settings with raw webpack externals settings was working :(

1__yarn_run_encore_dev_--watch__ssh_

@tristanbes
Copy link
Author

tristanbes commented Nov 12, 2017

Ok, so it seems I can play with webpack configuration itself:

var config = Encore.getWebpackConfig();
config.watchOptions = { poll: 400, ignored: /node_modules/ };
config.externals = {
  vue: 'Vue',
  vuex: 'Vuex',
  google: 'google',
  leaflet: 'L',
  markerclustererplus: 'MarkerClusterer',
  routing: 'Routing',
  app: 'app',
  translator: 'Translator',
};

config.resolve.alias = {
  ...config.resolve.alias,
  Translator: 'node_modules/bazinga-translator/js',
};
// export the final configuration
module.exports = config;

Or maybe I missed something in the API ?

@Lyrkan
Copy link
Collaborator

Lyrkan commented Nov 12, 2017

Hi @tristanbes,

Currently there is no "helper method" to directly manipulate externals and aliases.

We add some aliases for Vue.js and Preact but that's all:

config.resolve = {
extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'],
alias: {}
};
if (this.webpackConfig.useVueLoader) {
config.resolve.alias['vue$'] = 'vue/dist/vue.esm.js';
}
if (this.webpackConfig.usePreact && this.webpackConfig.preactOptions.preactCompat) {
config.resolve.alias['react'] = 'preact-compat';
config.resolve.alias['react-dom'] = 'preact-compat';
}

So if you really need them I guess you're doing it the right way :)

Note that you can also use FOSJsRoutingBundle without externals/aliases:

@weaverryan
Copy link
Member

Adding aliases and externals seems common enough that I think it makes sense to add mutators to the Encore API. Wdyt @Lyrkan?

@Lyrkan
Copy link
Collaborator

Lyrkan commented Nov 14, 2017

Yep, we should probably implement addAliases() and addExternals() 👍

@Lyrkan Lyrkan added the Feature New Feature label Nov 14, 2017
@ddproxy
Copy link

ddproxy commented Nov 17, 2017

I'm struggling with adding aliases right now, I'd expect

config.resolve.alias = {
    'App': path.resolve('./app/Resources/src/App')
};

To resolve my import * from 'App/Module'; into ./app/Resources/src/App/Module.js (converting over from requirejs) but it doesn't seem to be picking it up, anywhere.

@Lyrkan
Copy link
Collaborator

Lyrkan commented Nov 17, 2017

Hi @ddproxy,

First thing to check: are you exporting the right config?

// Bad
const config = Encore.getWebpackConfig();
config.resolve.alias = { /* ... */ };
module.exports = Encore.getWebpackConfig();

// Good
const config = Encore.getWebpackConfig();
config.resolve.alias = { /* ... */ };
module.exports = config;

Then: is path.resolve() returning the right path? Try adding a console.log(...) in your webpack.config.js file to display it when running encore.

@ddproxy
Copy link

ddproxy commented Nov 17, 2017

Adding a bit more information just in case, but yes I'm exporting the correct configuration object. At this point I'm mucking around the webpack config docs, tweaking different advanced settings (such as symlink: true)...

config.resolve.alias = {
    ...config.resolve.alias,
    'App': path.resolve('./app/Resources/src/App')
};

if (Encore.isProduction()) {
    config.plugins = config.plugins.filter(
        plugin => !(plugin instanceof webpack.optimize.UglifyJsPlugin)
    );

    config.plugins.push(new UglifyJsPlugin());
}

module.exports = config;

@ddproxy
Copy link

ddproxy commented Nov 17, 2017

More information!

My App structure doesn't have index.js modules for each directory.

IE: App/Backbone/Backbone doesn't have
App/Backbone/index.js
App/Backbone/Backbone/index.js
files.

Using

config.resolve.alias['App'] = path.resolve(__dirname, './app/Resources/src/App');

according to the webpack docs (https://webpack.js.org/configuration/resolve/#resolve-alias) is supposed to map the following (shortened list)...

Alias import from 'App/Backbone/Backbone' import from 'App/Backbone/Backbone.js'
{ App: "/absolute/App" } /absolute/App/Backbone/Backbone/index.js /absolute/App/Backbone/Backbone.js

But, after some testing, (by adding an index.js) it doesn't work that way right off the back. If I were to use the App/Backbone/Backbone.js import - my errors go away... Not the fix I was looking for (plenty of imports to add 'js' to) but I can keep moving forward with this.

Edit: adding .js also didn't work... Just threw an error a bit further down.

@ddproxy
Copy link

ddproxy commented Nov 17, 2017

Well, uh... This is embarrassing... It'd be nice if I used the right path. My issue is resolved now.

@Lyrkan Lyrkan added the HasPR label Nov 25, 2017
weaverryan added a commit that referenced this issue Feb 11, 2018
…yrkan)

This PR was merged into the master branch.

Discussion
----------

Add Encore.addAliases and Encore.addExternals methods

This PR adds two new methods to the API (closes #200):

* **`Encore.addAliases`**: Adds the given values to the `resolve.alias` setting of the generated config
* **`Encore.addExternals`**: Adds the given values to the `external` setting of the generated config

Commits
-------

eefe8a4 Add Encore.addAliases and Encore.addExternals methods
@MartinLyne
Copy link

Is there a way to install this with flex or composer yet, please?

@Lyrkan
Copy link
Collaborator

Lyrkan commented Sep 26, 2018

Hi @MartinLyne,

Encore.addAliases and Encore.addExternals were added in Encore 0.18.0, and the current flex pack automatically installs Encore 0.20.1.

If you are talking about an existing Flex install, then you'll have to update it manually using yarn or npm.

@MartinLyne
Copy link

MartinLyne commented Sep 27, 2018

If I try to manually use that version number with yarn add I get [1/5] Resolving packages... error Received malformed response from registry for undefined. The registry may be down.

If I do yarn upgrade nothing updates. Sorry, thanks for any help.

Edit: sorry it seems I was using incorrect yarn reference (using the composer name without "pack" at the end.

@Lyrkan
Copy link
Collaborator

Lyrkan commented Sep 27, 2018

Hm, I just tried it an it works fine:

$ yarn add --dev @symfony/webpack-encore@^0.20.1
(...)
success Saved 534 new dependencies.
info Direct dependencies
└─ @symfony/[email protected]
info All dependencies
├─ @symfony/[email protected]
├─ @types/[email protected]
(...)
├─ [email protected]
├─ [email protected]
└─ [email protected]
Done in 92.67s.

Are you behind a proxy or something else that could block yarn?
Is your yarn configured to use a private registry (other than npm)?

@MartinLyne
Copy link

Wait.. you didn't have to use -pack suffix?

I also updated nodejs, if that is relevant (i was at the bottom of the barrel)

So I just removed the symfony/webpack-encore-pack that I added (from a stack overflow answer) and encore + externals still works. So I guess it was nodejs version (I only installed it the other day, strange). Wish I'd used verbose earlier to see what was generating that undefined.

@stof
Copy link
Member

stof commented Sep 27, 2018

symfony/webpack-encore-pack is just a way for the Flex recipe to initialize the package.json file to reference encore. But webpack-encore is not a PHP package at all, but a node.js one. So installing it is done using the node.js tooling (npm or yarn).

@FullStackAlex
Copy link

FullStackAlex commented Dec 28, 2018

In my case "./" before the path caused the issue.
After removing it from the path string, Webpack finally resolves the alias!! 🎉

let config = Encore.getWebpackConfig();
config.resolve.alias["~"] = path.resolve(__dirname, 'assets/js');
module.exports = config;

And then just like this:

import Header from '~/components/Header.vue'

More Info here:
https://webpack.js.org/configuration/resolve/
https://symfony.com/doc/current/frontend/encore/advanced-config.html

@dadaxr
Copy link

dadaxr commented Feb 25, 2020

Could be nice to have a doc entry about addAliases and addExternals (#217 ) in the https://symfony.com/doc/current/frontend/encore/advanced-config.html .

The actual comment about the feature is quite hidden !

@nerdess
Copy link

nerdess commented Aug 16, 2024

Also, keep in mind when you define sth as an external, you have to add it manually.

Here is an example with bootstrap:

In webpack.config.js

Encore
.addExternals({
   bootstrap: 'bootstrap'
})
.addPlugin(new CopyWebpackPlugin({
        patterns: [
            { from: './node_modules/bootstrap/dist/js/bootstrap.bundle.min.js', to: 'bootstrap.bundle.min.js' }
        ]
 }))

In your main template
<script src="{{ asset('build/bootstrap.bundle.min.js') }}"></script>

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

Successfully merging a pull request may close this issue.

9 participants