簡體   English   中英

使用Webpack的VueJS:導入和導出未按預期工作

[英]VueJS with Webpack: imports and exports not working as expected

我啟動了一個新的Vuetify / Webpack項目,並在通過vue init vuetify/webpack設置項目后嘗試實現vue-router

我根據本教程的說明設置了路由器。 在一些擺弄之后,我通過改變導入Vue組件的方式來實現它。

在我的router/index.js文件中:

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

// does NOT work; from the tutorial
import Main from '@/components/Main'

我的問題是,為什么我必須相對導入我的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

我的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' } 

您正在嘗試從名為@別名目錄加載文件。 但是在您的webpack配置文件中,您尚未定義該別名。

此外,您需要指定.vue擴展名,因為您尚未將其添加到配置對象的resolve屬性中的可解析extensions中。

webpack.config.js文件中,添加要解析的擴展列表以及一個名為@的別名,該別名映射到您的src目錄:

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

編輯:@evetterdrake告訴我,當使用vue-cli設置Vuetify項目時, resolve config屬性位於module屬性之后,這與設置普通Webpack項目時不同。

請務必將這些配置選項添加到現有的resolve屬性中,否則它將被覆蓋並被忽略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM