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

时间:2018-03-15 14:02:43

标签: javascript webpack vue.js lodash nuxt.js

我们已经构建了一个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文件。仅包括相关/重要部分:

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`

    }
  }
}

1 个答案:

答案 0 :(得分:4)

您只能npm install所需的套餐

Lodash可按custom builds拆分。您可以找到已有的here列表。您可以像这样使用它们:npm i -S lodash.orderby。我没有检查过,但您可能还需要将import orderBy from 'lodash/orderBy'更改为import orderBy from 'lodash.orderby'