项目目录

image.png

package.json

  1. {
  2. "name": "webpack-vue",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "webpack.config.js",
  6. "scripts": {
  7. "build": "webpack --config webpack.config.js"
  8. },
  9. "author": "",
  10. "license": "ISC",
  11. "devDependencies": {
  12. "css-loader": "^3.2.0",
  13. "mini-css-extract-plugin": "^0.8.0",
  14. "style-loader": "^1.0.0",
  15. "vue": "^2.6.10",
  16. "vue-loader": "^15.7.1",
  17. "vue-template-compiler": "^2.6.10",
  18. "webpack": "^4.39.3",
  19. "webpack-cli": "^3.3.7"
  20. }
  21. }
  • vue-loader和vue-template-compiler需一起使用,用于编译.vue文件
  • css-loader或style-loader处理样式
  • mini-css-extract-plugin:将vue里的CSS提取出来,整合成一个css文件
  • 编译打包执行:npm run build

webpack.config.js

  1. const path = require('path');
  2. const VueLoaderPlugin = require('vue-loader/lib/plugin')
  3. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  4. module.exports = {
  5. mode: 'production',
  6. entry: './src/main.js', //webpack读取的入口文件
  7. output: { //打包输出文件路径
  8. path: path.resolve(__dirname, 'dist'),
  9. filename: 'index.js'
  10. },
  11. module: {
  12. rules: [
  13. {
  14. test: /\.vue$/,
  15. use: 'vue-loader',
  16. },
  17. {
  18. test: /\.css$/,
  19. use: [
  20. MiniCssExtractPlugin.loader,
  21. "css-loader"
  22. ]
  23. }
  24. ]
  25. },
  26. plugins: [
  27. new VueLoaderPlugin(),
  28. new MiniCssExtractPlugin({
  29. filename: "style.css",
  30. chunkFilename: "[id].css"
  31. })
  32. ],
  33. resolve: {
  34. extensions: ['.js','.json','.vue'],
  35. },
  36. }

main.js

  1. import Vue from 'vue';
  2. import App from './App'
  3. new Vue({
  4. el: '#app',
  5. render: h => h(App)
  6. })

App.vue(vue入口文件)

  1. <template>
  2. <div>
  3. <p>{{msg}}</p>
  4. <input type="text" v-model="msg">
  5. <button class="btn">按钮</button>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data(){
  11. return {
  12. msg: "Hello,world"
  13. }
  14. },
  15. }
  16. </script>
  17. <style>
  18. .btn{
  19. color:red;
  20. }
  21. </style>

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>搭建vue开发环境</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
  7. <link rel="stylesheet" href="./dist/style.css"/>
  8. </head>
  9. <body>
  10. <div id="app">
  11. </div>
  12. <script src="./dist/index.js"></script>
  13. </body>
  14. </html>

webpack-vue.zip