使用Webpack的VueJS:导入和导出未按预期工作

eve*_*ake 6 javascript vue.js vue-router vuejs2 vuetify.js

我开始了一个新的Vuetify/Webpack项目,并尝试vue-router在设置项目之后实现vue init vuetify/webpack.

我根据本教程的说明设置了路由器.在一些摆弄之后,我通过改变导入Vue组件的方式来实现它.

在我的router/index.js档案中:

// works for me
import Main from '../components/Main.vue'

// does NOT work; from the tutorial
import Main from '@/components/Main'
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么我必须Main.vue相对导入我的文件并包含.vue extension导入?


我的项目结构:

-node_modules/
-public/
-src/
|-components/
||-Main.vue
|-router/
||-index.js
|-App.vue
|main.js
-index.html
-package.json
-webpack.config.js
Run Code Online (Sandbox Code Playgroud)

我的webpack.config.js文件:

var path = require('path')
var webpack = require('webpack')
 
module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  resolve: {
    alias: {
      'public': path.resolve(__dirname, './public')
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          objectAssign: 'Object.assign'
        }
      },
      {
        test: /\.styl$/,
        loader: ['style-loader', 'css-loader', 'stylus-loader']
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}
Run Code Online (Sandbox Code Playgroud)

tha*_*ksd 3

您正在尝试从名为 的别名目录加载文件@。但在您的 webpack 配置文件中,您尚未定义该别名。

此外,您还需要指定.vue扩展名,因为您尚未将其添加到配置对象的属性extensions中的可解析项中。resolve

在您的webpack.config.js文件中,添加要解析的扩展名列表以及映射@到您的src目录的别名:

resolve: {
  extensions: ['', '.js', '.vue'],
  alias: {
    '@': path.resolve(__dirname, './src'),
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:@evetterdrake 告诉我,当使用vue-cliVuetify 设置项目时,resolveconfig 属性位于module属性之后,这与设置普通 Webpack 项目时不同。

请务必将这些配置选项添加到现有resolve属性中,否则它将被覆盖并忽略。