【问题标题】:vue cli how to create a custom chunk and hook in index.html?vue cli 如何在 index.html 中创建自定义块和挂钩?
【发布时间】:2020-06-29 06:11:59
【问题描述】:

我想创建一个自定义块并附加到生成的 index.html 中。我使用vue create . 创建了一个自定义项目并添加了一个vue.config.js 文件。

vue.config.js

module.exports = {
  lintOnSave: true,
  configureWebpack: {
    optimization: {
      splitChunks: {
        cacheGroups: {
          utiltest: {
            name: 'utiltest',
            test: /utils[\\/]test/,
            priority: -30,
            chunks: 'initial',
          },
        },
      },
    },
  },
};

我在src/utils/test 中有一些实用程序函数,我想为此创建一个单独的包并附加到 index.html 中。像这样

<script type="text/javascript" src="/js/chunk-utiltest.js"></script>
<script type="text/javascript" src="/js/chunk-vendors.js"></script>
<script type="text/javascript" src="/js/app.js"></script>

但是在生成的 index.html 文件中它没有为 utiltest 创建块,它只有这 2 个

<script type="text/javascript" src="/js/chunk-vendors.js"></script>
<script type="text/javascript" src="/js/app.js"></script>

注意:我在 main.js 中从 utils/test 导入函数,例如

import testHook from '@/utils/test';
...
testHook();

【问题讨论】:

    标签: vue.js webpack webpack-splitchunks


    【解决方案1】:

    如果您只是想创建一个新块,则添加另一个入口点。现在输出目录中有两个文件可用。 public/index.jspublic/untiltest.js

    module.exports = (env, options) => ({
      entry: {
        index: './src/index',
        utiltest: './src/utiltest',
      },
      output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'public'),
      },
      ....
      
    

    你也可以name the chunks你想在vue中导入

    const routeOptions = [
      { path: '/', name: 'Home' },
      { path: '/about', name: 'About' },
      { path: '/login', name: 'Login' }
    ]
    
    const routes = routeOptions.map(route => {
      return {
        ...route,
        component: () => import(/* webpackChunkName: "[request]" */ `../views/${route.name}.vue`)
      }
    })
    
    const router = new VueRouter({
      routes
    })
    

    在普通的 html 文件中,您也可以将其与 html webpack plugin 结合使用

      ...
      new HtmlWebpackPlugin({
        title: 'Vue App',
        template: './src/template.html',
        filename: 'index.html',
        chunks: ['index', 'utiltest'],
      }),
    

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2020-05-28
      • 2023-01-18
      • 2022-09-27
      • 2023-03-11
      • 2022-12-10
      • 2020-08-04
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多