用webpack解析.vue單文件

首先建立項目文件夾 vueTest,執行:css

cd vueTest && npm init

安裝webpack和vuehtml

npm i -D webpack
npm i -D webpack-cli
npm i -S vue

建立下面的項目目錄:vue

App.vue :node

<template>
    <h1>Hello {{ msg }}</h1>
</template>
<script>
    export default {
        data(){
            return {
                msg: 'Vue.js'
            }
        }
    }
</script>
<style scoped>
    h1{
        font-family: 'Courier New';
        color: red;
    }
</style>

main.js :webpack

import Vue from 'vue';
import App from './App.vue';

new Vue({
    el: '#app',
    render: h => h(App)
});

而後開始寫webpack配置文件,寫以前先安裝各類loaderweb

npm i -D vue-loader css-loader vue-template-compiler

還須要用extract-text-webpack-plugin插件將vue文件中的樣式提取出來npm

npm i -D extract-text-webpack-plugin

若是webpack版本是4.0及以上請執行下面的命令:json

npm i -D extract-text-webpack-plugin@next

webpack.config.js :瀏覽器

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: './main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist'),
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: ['vue-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader']
                }),
                exclude: /node_modules/
            }
        ]
    },
    plugin: [
        new VueLoaderPlugin(),
        new ExtractTextPlugin('style.css')
    ]
}

而後在package.json裏寫一個啓動腳本app

{
    "name": "vuetest",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --config webpack.config.js"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "css-loader": "^1.0.0",
        "extract-text-webpack-plugin": "^4.0.0-beta.0",
        "vue-loader": "^15.2.6",
        "vue-template-compiler": "^2.5.17",
        "webpack": "^4.16.4",
        "webpack-cli": "^3.1.0"
    },
    "dependencies": {
        "vue": "^2.5.17"
    }
}

執行  npm run build 便可成功編譯:

編譯後的項目結構:

在index.html中寫入:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="./dist/style.css">
</head>
<body>
    <div id="app"></div>
    <script src="./dist/bundle.js"></script>
</body>
</html>

打開瀏覽器就看看到效果了:

相關文章
相關標籤/搜索