Search code examples
vue.jsvuejs3

opening vue 3 inside bootstrap modal - SyntaxError: Identifier 'createApp' has already been declared


when page1 with vue loads page2 with vue in a bootstrap modal it errors out with:

SyntaxError: Identifier 'createApp' has already been declared

page1.html:

<script>
    const {
        createApp,
        ref
    } = Vue
    createApp({
        setup() {
            const user_id = ref();
            return {
                user_id
            }
        }
    }).mount('#app_page1');
</script>

page2.html:

<script>
    const {
        createApp,
        ref
    } = Vue
    createApp({
        setup() {
            const files = ref();
            return {
                files
            }
        }
    }).mount('#app_page2');
</script>

Solution

  • const inside <script> creates global variables that cannot be redeclared.

    A way to avoid this is to use scoped variables in all embedded scripts, e.g. with a block:

    <script>
    {
        const {
            createApp,
            ref
        } = Vue
        ...
    }
    </script>
    

    For an unbundled app that uses Vue CDN a less quirky way is to use native modules, this won't require to use blocks due to how variable scopes work in ES modules, e.g. for embedded scripts:

    <script type="module">
    const {
        createApp,
        ref
    } = Vue
    ...