如何在Shopware 6中使用Webpack加载单独的JS文件以提高网站性能?

huangapple go评论51阅读模式
英文:

How can I use Webpack to load a separate JS file in Shopware 6 and improve web performance?

问题

如何在Shopware 6中使用Webpack加载单独的JS文件?

什么?

我正在尝试使用Webpack在all.js文件旁边加载一个单独的javascript文件。

为什么?

all.js文件可能会变得非常大,你正在在页面上加载不必要的javascript。因此,通过使用代码拆分(由于Shopware 6中已经实现了Webpack,这应该是可能的),以及动态导入,你可以停止加载不必要的javascript。

我尝试过的

我在我的主题插件的根目录中添加了一个webpack.config.js文件,如下所示:

module.exports = {

    entry: {
        main: './src/main.js', 
        separateFile: './src/js/separate.js'
    },

    output: {
        filename: '[name].js'
    },

    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
};

在运行bin/build-storefront.sh之后,公共文件夹中没有添加单独的JS文件。

我还尝试在src/Resources/app/storefront/src/main.js中动态加载此JS文件,但由于单独的文件不存在,这导致了404错误。

英文:

How to load a separate JS file in Shopware 6 using webpack?

What?

I'm trying to load a separate javascript file next to the all.js file by using WebPack.

Why?

The all.js file can get really big and you're loading unnecessary javascript on a page. So by using code splitting (which should be possible since WebPack is implemented in Shopware 6) and dynamic imports you could stop loading unnecessary javascript.

What I've tried

I've added a webpack.config.js file inside the root of my theme plugin like so:

module.exports = {

    entry: {
        main: './src/main.js', 
        separateFile: './src/js/separate.js'
    },

    output: {
        filename: '[name].js'
    },

    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
};

After running bin/build-storefront.sh there is no separate JS file added in the public folder.

I'm also trying to dynamically load this JS file in src/Resources/app/storefront/src/main.js but this results in a 404 since the separate file doesn't exist.

答案1

得分: 0

这将无法正常工作,因为所有插件的预编译资源都会被收集到ThemeCompiler中,并合并成一个单独的脚本。这是在PHP中完成的,因为在生产环境中不需要Node。

您可以尝试将单独的脚本添加为额外的自定义资源,但仍然需要手动扩展模板以添加相应的script标签。

英文:

This will not work since all pre-compiled assets of plugins are collected in the ThemeCompiler and concatenated into one single script. This is done in PHP since node is not a requirement for production environments.

You could try to add separate scripts as additional custom assets, but you would still have to extend the template to add the corresponding script tags manually.

huangapple
  • 本文由 发表于 2023年6月1日 21:40:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定