简体   繁体   中英

VueJS with Webpack: imports and exports not working as expected

I started a new Vuetify / Webpack project, and tried to implement vue-router after setting up a project via vue init vuetify/webpack .

I set up the router based on the instructions from this tutorial . After some fiddling, I got it working by changing the way I imported Vue components.

In my router/index.js file:

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

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

My question is, why do I have to import my Main.vue file relatively and include the .vue extension on the import?


My project structure:

-node_modules/
-public/
-src/
|-components/
||-Main.vue
|-router/
||-index.js
|-App.vue
|main.js
-index.html
-package.json
-webpack.config.js

My webpack.config.js file:

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

You are attempting to load a file from an alias directory named @ . But in your webpack config file, you haven't defined that alias.

Also, you are required to specify the .vue extension because you haven't added it to the resolvable extensions in the resolve property in your config object.

In your webpack.config.js file, add a list of extensions to resolve and an alias called @ which maps to your src directory:

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

Edit: @evetterdrake informed me that when using vue-cli to set up a project with Vuetify, the resolve config property is positioned after the module property, which is different than when setting up a normal Webpack project.

Be sure to add these config options to the existing resolve property or it will be overwritten and ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM