首页 > 解决方案 > 将模块导入 vue.config.js

问题描述

我想导入 npm 包 vue-remove-attributes 以从 DOM 中删除我的“data-testid”属性。https://www.npmjs.com/package/vue-remove-attributes

在自述文件中,他们说我必须在我的 webpack 配置中将模块传递给 vue-loader。我已经安装了 webpack,但我唯一的配置文件是 vue.config.js,它看起来像这样:

module.exports = {
  publicPath: "./",
  productionSourceMap: false,
  lintOnSave: process.env.NODE_ENV !== "production",
}

我尝试像这样导入模块

const createAttributeRemover = require('vue-remove-attributes');

module.exports = {
  publicPath: "./",
  productionSourceMap: false,
  lintOnSave: process.env.NODE_ENV !== "production",

  configureWebpack: {
    plugins: new createAttributeRemover(),
    module: {
      rules: [
        {
          test: /\.vue$/,
          use: {
            loader: "vue-loader",
            options: {
              compilerOptions: {
                modules: [createAttributeRemover("data-testid")]
              }
            }
          }
        }
      ]
    }
  },
};

但这似乎不起作用。有什么想法可以在我的 vue 配置中导入 npm 包吗?

标签: javascriptnode.jsvue.jsnpmwebpack

解决方案


您没有标记vue-cli,但您正在使用该configureWebpack属性,所以我假设您是。您需要修改现有的加载程序规则。您可以通过链接来利用它并添加您的选项:

chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
        .tap(options => {
          // modify the options...
          options.compilerOptions.modules = [createAttributeRemove('data-testid')]
          return options
        })

推荐阅读