【问题标题】:Vue loaded twice with Webpack-compiled libraryVue 使用 Webpack 编译的库加载了两次
【发布时间】:2020-11-10 05:06:02
【问题描述】:

我有 Vue 组件的 TypeScript 库,它使用 Webpack 编译为单个 JS 文件。使用该库的 TypeScript 项目也依赖于 Vue。运行应用程序时,我可以看到加载了两个 vue 实例,一个包含在库包中 (/node_modules/my-lib/dist/index.js),另一个来自项目的 node_modules (/node_modules/vue/dist/vue.esm.js)。

库的webpack.config.js:

const path = require('path');
module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'index.js',
        publicPath: '/dist/',
        path: path.resolve(__dirname, 'dist'),
        library: "fsaa-util",
        libraryTarget: 'umd',
        umdNamedDefine: true
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    allowTsInNodeModules: true,
                    appendTsSuffixTo: [/\.vue$/]
                }
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.vue', '.wasm', '.mjs', '.js', '.json', 'css'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
        },
        modules: ["src", "node_modules"]
    },
};

消费者项目的webpack.config.js:

const path = require('path');
module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'index.js',
        publicPath: '/dist/',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    allowTsInNodeModules: true,
                    appendTsSuffixTo: [/\.vue$/],
                    compiler: 'ttypescript'
                }
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.vue', '.wasm', '.mjs', '.js', '.json', 'css'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
        },
        modules: ["src", "node_modules"]
    }
};

如何在库和消费者项目中导入 vue:

import Vue from "vue";

按照其他地方的建议,我也尝试使用:

externals: {
    vue: 'vue',
},

在库的 webpack.config.js 中,但我都加载了 vue.runtime.esm.jsvue.esm.js

【问题讨论】:

    标签: typescript vue.js webpack


    【解决方案1】:

    我遇到了类似的问题,结果我通过两种方式将 Vue 导入到我的组件中:

    import Vue from "vue";
    

    import Vue from "Vue";
    

    “Vue”中的 PascalCase 导致错误,所有其他模块都导入“vue”。这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 2019-03-22
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多