打包组件报错:Error: Cannot find module ‘vue/compiler-sfc‘

vue组件库搭建过程中使用webpack打包组件时报错,报错内容如下:

Error: Cannot find module 'vue/compiler-sfc'
Require stack:
- D:\vue2\moon-ui\node_modules\vue-loader\dist\index.js
- D:\vue2\moon-ui\webpack.config.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (D:\vue2\moon-ui\node_modules\vue-loader\dist\index.js:8:24)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'D:\\vue2\\moon-ui\\node_modules\\vue-loader\\dist\\index.js',
    'D:\\vue2\\moon-ui\\webpack.config.js'
  ]
}

发现报错文件:webpack.config.js

const path = require("path");
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const glob = require("glob");
const list = {};
​
async function makeList(dirPath, list) {
    const files = glob.sync(`${dirPath}/**/index.js`)
    for (const file of files) {
        const component = file.split(/[/.]/)[2];
        list[component] = `./${file}`;
    }
}
makeList("components/lib", list)
module.exports = {
    entry: list,
    output: {
        filename: '[name].umd.js',
        path: path.resolve(__dirname, "dist"),
        library: 'mui',
        libraryTarget: 'umd'
    },
    plugins: [
        new VueLoaderPlugin(),
    ],
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: [
                    { loader: 'vue-loader' },
                ]
            }
        ]
    }
};

通过执行下面代码,测试当前文件是否可执行:

node webpack.config.js

发现当引入VueLoaderPligin时报错

const VueLoaderPlugin = require('vue-loader/lib/plugin');

查询发现package.json中vue-loader版本是17.0.0:

{
  ...
  "devDependencies": {
    ...
    "vue-loader": "^17.0.0",
    ...
  }
}

解决方法

npm i vue-loader@15 -D

安装低版本的vue-loader

重新尝试打包,解决问题!

你可能感兴趣的:(webpack,web,前端,vue.js,webpack,javascript)