我们如何在 Nuxt?Vuejs 项目中仅包含来自 lodash 的必需模块?

How do we include only required modules from lodash in a Nuxt?Vuejs Project?

我们已经构建了一个 Nuxt/VueJS 项目。

Nuxt 有自己的配置文件 nuxt.config.js,我们可以在其中配置 webpack 和其他构建设置。

在我们的 package.json 中,我们包含了 lodash 包。

在我们的代码中,我们一直小心地只加载导入我们需要的内容,例如:

import orderBy from 'lodash/orderBy'

nuxt.config.js中,lodash被添加到vendor列表中。

然而,当我们创建构建时,webpack 总是包含整个 lodash 库,而不是仅包含我们在代码中使用的内容。

我已经阅读了很多教程,但还没有找到答案。如果它只是一个 webpack 项目,那么其中一些答案肯定会起作用。但在我们的例子中,它是通过 nuxt 配置文件。

期待一些帮助。

下面是部分 nuxt.config.js 文件。仅包含 relevant/important 部分:

const resolve = require('resolve')
const webpack = require('webpack')

module.exports = {
  /*
  ** Headers of the page
  */
  head: {
  },
  modules: [
    ['@nuxtjs/component-cache', { maxAge: 1000 * 60 * 10 }]
  ],
  plugins: [
    { src: '~/plugins/intersection', ssr: false },
  ],
  build: {
    vendor: ['moment', 'lodash'],
    analyze: {
      analyzerMode: 'static'
    },
    postcss: {
      plugins: {
        'postcss-custom-properties': false
      }
    },
    plugins: [
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
    ],
    /*
    ** Run ESLINT on save
    */
    extend (config, ctx) {
      // config.resolve.alias['create-api'] = `./create-api-${ctx.isClient ? 'client' : 'server'}.js`

    }
  }
}

您可以npm install 只需要所需的包

Lodash 可以按照 custom builds. You can find a list of already available ones here 拆分。您可以像这样使用它们:npm i -S lodash.orderby。我没有检查,但您可能还需要将 import orderBy from 'lodash/orderBy' 更改为 import orderBy from 'lodash.orderby'