欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webpack打包vue项目实战入门

程序员文章站 2022-05-30 16:39:27
...

项目目录

G:.
│  index.html
│  package.json
│  webpack.config.js
│
└─src
    │  router.js
    │
    ├─components
    │      find.vue
    │      home.vue
    │      mine.vue
    │
    ├─js
    │      entry.js
    │
    └─views
            app.vue
            index.vue
            login.vue

index.html

<div id="app">
    </div>

package.json

{
  "name": "webpack_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "webpack-dev-server --open --hot"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "url-loader": "^2.2.0",
    "vue": "^2.6.10",
    "vue-loader": "^15.7.1",
    "vue-router": "^3.1.3",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.9.0"
  },
  "devDependencies": {
    "css-loader": "^3.2.0",
    "style-loader": "^1.0.0"
  }
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
  entry:'./src/js/entry.js',
  output: {
    path: path.resolve(__dirname, 'dist/js'),
    filename: 'bundle.js',
    // publicPath:'js/'//打包后资源的路径
  },
  devServer: {
    contentBase: path.join(__dirname, "dist"),//webpack-dev-server服务的index.html所在目录
    compress: true,
    port: 9000
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({ template: './index.html' }),//被打包文件
    new CleanWebpackPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        exclude:/node_modules/
      },
      {
        test: /\.(png|jpg|gif)$/, use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192//图片小于8192时被打包进入js文件中
            }
          }
        ]
      }
    ]
  },
  mode: "production",
  performance: {
    hints:false   
  }
}

entry.js入口文件

import Vue from 'vue'
import App from '../views/app.vue'
import router from '../router.js'
new Vue({
    router,
    render: h => h(App),
  }).$mount('#app')//将App挂载在index.html的id为app的元素的位置上