绵阳动力网站建设

vue组件使用webpack打包组件时报Error:Cannot find module 'vue/compiler-sfc'错误的解决办法

时间:2024-01-08

最近遇到这样的问题,vue组件库搭建过程中使用webpack打包组件时报错:Error: Cannot find module ‘vue/compiler-sfc‘,通过参考官方资料和网上搜索最终解决了这个错误,现将解决过程分享出来,如果你也遇到这类的错误,可以参考。

1、打包错误:

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.<anonymous> (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'
  ]
}

2、查找错误文件:

找寻报错路径,发现报错文件: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",    
...    
}    
}

3、解决办法:

安装低版本的vue-loader

npm i vue-loader@15 -D

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

好了,vue组件使用webpack打包组件时报Error:Cannot find module 'vue/compiler-sfc'错误的问题就按照上述步骤就可以解决了!

Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号

客服微信
客服微信
0816-6339181
客服微信
my_dongli