Home > Net >  Configure webpack to read / load xlsx files in vue project
Configure webpack to read / load xlsx files in vue project

Time:08-27

I have some trouble to read a local .xlsx file in my Vue project. My project contains a local .xlsx file, and I would like to read / parse it when the component is created(). However, my terminal gives me an error :

Module parse failed: Unexpected character '♥' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

It seems like I need to configure webpack, but I haven't found any resource about xlsx loader. Here is the content of my vue.config.js file :

const { defineConfig } = require('@vue/cli-service')
const path = require('path');

module.exports = defineConfig({
  transpileDependencies: true,

  pluginOptions: {
    'style-resources-loader': {
        preProcessor: 'scss',
        'patterns': [
            path.resolve(__dirname, './src/styles/setup/*.scss'),
        ]
    }
  },

  chainWebpack: (config) => {
    config
    .module
      .rule("svg")
        .set('generator', {
          filename: "[contenthash][ext]"
        })
  },
})

I guess I need to add a "config" to the chainWebpack object, but what can I write inside ? Thanks for the help !

CodePudding user response:

Ok I managed to find a way :

  chainWebpack: (config) => {
    config.module
      .rule("svg")
      .set('generator', {
        filename: "[contenthash][ext]"
      })

    config.module
    .rule('file')
    .test(/\.(xlsx|xls|csv)(\?.*)?$/)
    .set('type', 'asset')
    .set('generator', {
      filename: "[contenthash][ext]"
    })
  },

I don't really what does the .set functions really do, but it works. If anyone can bring an explanation, I'd appreciate !

  • Related