使用 webpack 编译 vue 页面

1,346 阅读1分钟

背景

需要使用原生的 javascript 来调用 vue 组件。目前思路使用 webpack 将 vue 组件打包,然后使用 js 文件 引入打包。最后在 html 中引入最终打包好的文件。

环境安装

以下是 package.json 文件内容

{
  "name": "vue-originjs-mix-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "babel-loader": "^8.2.2",
    "vue": "^2.6.12",
    "vue-cli": "^2.9.6",
    "vue-loader": "^15.9.6",
    "vue-template-compiler": "^2.6.12",
    "webpack": "^5.28.0",
    "webpack-cli": "^4.6.0"
  }
}

webpack编写

以下是 webpack.config.js 文件

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
	entry: "./index.js",
	output: {
		filename: "build.js",
		path: path.resolve(__dirname, 'build'),
	},
	module: {
            rules: [{
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        'less': ['style-loader!css-loader!less-loader'],
                        'css': [
                            'style-loader!css-loader'
                        ]
                    }
                }
            }]
        },
	mode: "development",
  plugins: [
    // 请确保引入这个插件来施展魔法
    new VueLoaderPlugin()
  ]
}

注意:需要引入 VueLoaderPlugin 这个插件,否则会报错。错误信息如下:

ERROR in ./test.vue?vue&type=template&id=13429420& 2:0 Module parse failed: Unexpected token (2:0) File was processed with these loaders:

小案例

  • 上述环境都安装好,创建 test.vue 文件

    //./test.vue
    <template>
    	<div>
    		{{initIndex}}
    	</div>
    </template>
    
    <script>
    export default {
        props: {
            initIndex: {
                type: Number,
                default: 0
            }
        },
        data() {
            return {};
        },
        created() {
        	console.log("created");
        }
    };
    </script>
    
    <style>
    	
    </style>
    
  • 创建 testJs.js 文件用于引入 vue 文件, 并且导出它

    // ./testJs.js
    import Vue from 'vue';
    import Test from './test.vue';
    
    export default function create(initIndex, selector) {
        return new Vue({
            el: selector,
            template: "<div><div>123</div><app-test :initIndex='initIndex'></app-test></div>",
            data() {
                return {
                    initIndex
                };
            },
            components: {
                appTest: Test
            }
        });
    }
    
    
  • 创建 index.js 文件用于引入 testJs.js

    import create from './testJs.js';
    
    create(5, "#test-wrapper")
    
  • 创建 index.html 引入 webpack 编译后的 js 文件

    //index.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    </head>
    <body>
    	<div id="test-wrapper"></div>
    	<!-- 引入打包后的js, 路径在webpack中设置 -->  
    	<script src="./build/build.js"></script>	
    </body>
    </html>
    
  • 使用 webpack 编译: webpack

  • 页面报错

    在浏览器中打开 index.html 页面, 打开控制台,报错内容如下:

    vue.runtime.esm.js:623 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

    (found in )

  • 解决错误

    造成错误的原因是:项目引入的vue的编译版本不对

    • 方案一:

      • 修改 webpack 配置添加别名

        resolve: {
          alias: {
          	vue: 'vue/dist/vue.esm.js'
          }
        }
        

        最终 webpack.config.js 文件为

        const path = require('path');
        const VueLoaderPlugin = require('vue-loader/lib/plugin');
        
        module.exports = {
            entry: "./index.js",
            output: {
                filename: "build.js",
                path: path.resolve(__dirname, 'build'),
            },
            module: {
                rules: [{
                    test: /\.vue$/,
                    loader: 'vue-loader',
                    options: {
                        loaders: {
                            'less': ['style-loader!css-loader!less-loader'],
                            'css': [
                                'style-loader!css-loader'
                            ]
                        }
                    }
                }]
            },
            mode: "development",
            resolve: {
                alias: {
                    vue: 'vue/dist/vue.esm.js'
                }
            },
            plugins: [
                // 请确保引入这个插件来施展魔法
                new VueLoaderPlugin()
            ]
        }
        
    • 方案二

      • 修改失败
    • 参考: 关于vue编译版本引入的问题

  • 最终页面呈现为

1.jpg