Search code examples
webpackrequirejsamd

How to ensure that AMD dependency has been loaded from inside <script> tag code?


I've migrated all the scripts that were included in my page to webpack bundle, and now I include only this.

How should I migrate my code (inside page <script> tags) in order to be compatible with AMD module loading? For example my existing code cannot access $ (jquery global object) anymore, (probably because it is not yet loaded) when the code runs.


Solution

  • You can use expose-loader module.

    Then in your webpack.config.js:

    module.exports = {
    
    
        module: {
    
            rules: [
                {
                    test: require.resolve('jquery'),
                        use: [{
                            loader: 'expose-loader',
                            options: '$'
                        },
                        {
                            loader: 'expose-loader',
                            options: 'jQuery'
                        }]
                },
    
            ]
        },