gpt4 book ai didi

javascript - 使用 Webpack 进行 Vue 异步导入

转载 作者:行者123 更新时间:2023-12-03 02:20:53 24 4
gpt4 key购买 nike

我有一个 VueJS 2 应用程序,我试图根据配置 JSON 文件中的不同标志加载特定组件。

我的文件结构如下:

root
config.json
> src
>> client
>>> components
>>>> dashboard
>>>>> MenuBarBrand.vue
> product
>> product01
>>> client
>>>> components
>>>>> branding
>>>>>> MenuBrand.vue
>> product02
>>> client
>>>> components
>>>>> branding
>>>>>> MenuBrand.vue

目前我尝试了两种不同的方法:

在我的 MenuBarBrand 组件中使用 webpack 导入语法:

<template>
<b-navbar-brand href="/dashboard">
<MenuBrand />
</b-navbar-brand>
</template>

<script>
import config from '../../../../config.json';
const MenuBrand = import(`../../../../product/${config.product}/components/branding/MenuBrand`);

export default {
name: 'MenuBarBrand',
components: {
'MenuBrand',
},
}
</script>

这会导致以下错误: Error

或 Vue 异步组件本地注册语法:

<template>
<b-navbar-brand href="/dashboard">
<MenuBrand />
</b-navbar-brand>
</template>

<script>
import config from '../../../../config.json';

export default {
name: 'MenuBarBrand',
components: {
'MenuBrand': () => import(`../../../../product/${config.product}/components/branding/MenuBrand`)
},
}
</script>

这会导致以下错误: Error

我是否犯了任何明显的错误,或者是否需要任何特定的 babel/webpack 插件来启用此功能?

编辑:根据我收到的评论添加我的加载器配置:

module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: [
'vue-style-loader',
'css-loader',
'sass-loader',
],
sass: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax',
],
},
},
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
},
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
},
{
test: /\.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]',
},
],
},

最佳答案

我通过另一种方法解决了这个问题。

在 webpack 配置中,我拉入我的产品标志并创建一个路径:

const config = require('./config.json');
const fs = require('fs');
const path = require('path');

const productPath = path.resolve(__dirname, 'product', config.product);

然后我使用以下路径在 webpack 配置中设置别名:

resolve: {
alias: {
menuBrandingPath: productPath,
},
extensions: ['*', '.js', '.vue', '.json'],
},

然后在我的 Vue 组件中使用此路径来导入正确的组件:

<template>
<MenuBrand />
</template>

<script>
import MenuBrand from 'menuBrandingPath/client/components/branding/MenuBrand'; // menuBrandingPath is an alias in the webpack config

export default {
name: 'MenuBar',
components: {
MenuBrand,
},
}
</script>

我故意省略了 fs 的错误检查和我用来使这个示例更容易理解的后备路径。希望它能帮助别人! :)

关于javascript - 使用 Webpack 进行 Vue 异步导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49163625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com