Vue Webpack开发可复用的单页面富应用教程(配置篇

来源:http://www.prospettivedarte.com 作者:计算机教程 人气:139 发布时间:2019-05-10
摘要:1.webpack是什么? 2.为什么要用webpack? 3.怎么用webpack? webpack是什么? 本文首发于 TalkingCoder ,一个有逼格的程序员社区。转载请注明出处和作者。 答:webpack是前端模块化应用和开发的

1.webpack是什么?
2.为什么要用webpack?
3.怎么用webpack?

皇牌天下投注网 1

webpack是什么?
皇牌天下投注网 2

本文首发于TalkingCoder,一个有逼格的程序员社区。转载请注明出处和作者。

答:webpack是前端模块化应用和开发的打包工具,解决前端模块依赖的工具。打包所有的脚本,图片,css。

写在前面

为什么要用webpack?
答:使用webpack可以让前端开发变得工程化和模块化,方便前端开发,提高开发速率。
webpack的主要优点是:模块化。
缺点是配置繁琐。

本文为系列文章,总共分四节:

怎么使用webpack?
答:参考官网文档:https://webpack.js.org/concepts/
或者中文文档:https://www.webpackjs.com/concepts/
看完后还不知道怎么用?请看我的使用例子。

《Vue Webpack使用规范》


《Vue Webpack开发可复用的单页面富应用教程(配置篇)》

本例中使用webpack的目的:
1.前端开发独立于后端使用webpack-dev-server,将页面可在本地查看,webpack-dev-server中的proxy,代理后端借口
2.用webpack的loader解析.vue后缀的文件
3.配置webpack的热更新,使得修改前端代码,页面自动更新
4.利用webpack-merge区分开发环境的配置和生产环境的配置
5.自动解析生产页面

《Vue Webpack开发可复用的单页面富应用教程(组件篇)》

webpack依赖webpack.config文件,生产环境和开发环境对应不用的位置文件,共同的配置文件放在一起
皇牌天下投注网 3

《Vue Webpack开发可复用的单页面富应用教程(技巧篇)》

src 目录
皇牌天下投注网 4

7月16日在斗鱼直播了一场关于Vue Webpack的技术分享,对基于vue的组件化开发有了一个初步的在线demo演示,点击查看直播录像。本文则会在此基础上,对Webpack的安装和基础配置进行较全面的讲解。

package.json文件中的配置

本系列文章所讲解内容,依赖于https://github.com/icarusion/vue-vueRouter-webpack这套架构,开发者可以前往进行clone或下载(记得star哦)。在使用中有疑问或更好的优化方案,可在https://github.com/icarusion/vue-vueRouter-webpack/issues这里提交。

  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --config ./webpack_config/webpack.config.development.js",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules --config ./webpack_config/webpack.config.production.js"
  },

关于vue vueRouter webpack


本项目可以帮你快速搭建一个基于Vue的单页面富应用,目前已将开发环境和生产环境进行单独配置(webpack.dev.config.js和webpack.prod.config.js),当然也可根据需要自行添加灰度配置文件。目前的开发环境文件名使用默认命名(比如1.chunk.js),生产环境使用带hash值的命名(比如1.0891dcfed66cf89e6e98.chunk.js),可根据自己需要修改,但不建议修改本地环境为带hash的。 入口的html文件由webpack生成,模板在src/template/index.html内,可自行修改。默认已将dist目录、生成的两个index文件加入忽略列表,使用者可根据自己项目来修改。

webpack.config.common.js中的配置

本项目默认将组件(components)、路由(routers)、自定义过滤器(filters)、自定义指令(directives)等单独拆成目录。在数据获取方面用户可以根据自己需要使用vue-resource或者jQuery等,如果是大型项目,还可以使用vuex来维护状态和数据。当然,这并不意味着本项目是最佳实践,所有的目录结构和webpack配置都可以根据自己需要来修改。

var path = require('path')
var webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin');

var glob = require('glob')
var files = glob.sync(path.resolve(__dirname, '../src/*/index.js'));
var newEntries = {};
const config = {
    entry: {
        vendor: [
            './public/bower_components/jquery/dist/jquery.js',
            './public/bower_components/bootstrap/dist/css/bootstrap.css',
            './public/bower_components/bootstrap/dist/js/bootstrap.js'
        ]
    },
    output: {
        path: path.resolve(__dirname, '../public/vue_dist/'),
        publicPath: '/vue_dist/',
        filename: '[name].js'
    },
    module: {
        rules: [{
                test: /.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ],
            },
            {
                test: /.scss$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'sass-loader'
                ],
            },
            {
                test: /.sass$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'sass-loader?indentedSyntax'
                ],
            },
            {
                test: /.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                        // the "scss" and "sass" values for the lang attribute to the right configs here.
                        // other preprocessors should work out of the box, no loader config like this necessary.
                        'scss': [
                            'vue-style-loader',
                            'css-loader',
                            'sass-loader'
                        ],
                        'sass': [
                            'vue-style-loader',
                            'css-loader',
                            'sass-loader?indentedSyntax'
                        ]
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(?. )?$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000
                    }
                }]
            },
            {
                test: path.resolve(__dirname, '../public/bower_components/jquery/dist/jquery.js'),
                use: [{
                    loader: 'expose-loader',
                    options: 'jQuery'
                }, {
                    loader: 'expose-loader',
                    options: '$'
                }]
            }
        ]
    },
    plugins: [
        new ManifestPlugin()
    ],
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
    },
    performance: {
        hints: false
    }
}
console.log(files   '------------files-------------------------');

files.forEach(function(f) {
    var name = /.*/(.*?/index).js/.exec(f)[1]; //register/main这样的文件名
    console.log(name   '------------name-------------------------');
    newEntries[name] = f;
});
console.log(newEntries   '------------newEntries-------------------------');

config.entry = Object.assign({}, config.entry, newEntries);



module.exports = config;

先把项目跑起来


准备工作

webpack.config.development.js 配置文件

使用前需要确保你安装了最新版的Node.jsnpm

const merge = require('webpack-merge');
const common = require('./webpack.config.common.js');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
var glob = require('glob')
var files = glob.sync(path.resolve(__dirname, '../src/*/index.js'));
var plugins = [];
files.forEach(function(f) {
    var name = /.*/(.*?/index).js/.exec(f)[1]; //register/main这样的文件名
    var plug = new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, '../public/vue_dist/'   name   '.html'),
        chunks: ['vendor', name],
        template: path.resolve(__dirname, '../src/index.html'),
        inject: true
    });
    plugins.push(plug);
});
plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor']
    }));
module.exports = merge(common, {
    plugins: plugins,
    devtool: '#eval-source-map',
    devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true,
        port: 8080,
        host: 'localhost',
        publicPath:'/vue_dist',
        proxy: [{
            context: ["/upload", "/phone",'/register','/users'],
            target: "http://127.0.0.1:3000",
        }],
        openPage: 'vue_dist/upload/index.html'
    },
    output: {
        path: path.resolve(__dirname, '../public/vue_dist/'),
        publicPath: '/vue_dist',
        filename: '[name].js'
    },
});

全局安装webpack和webpack-dev-server


npm install webpack -g

webpack.config.production.js 配置文件

npm install webpack-dev-server -g

const merge = require('webpack-merge');
const common = require('./webpack.config.common.js');
const path = require('path');
var webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
var fillter = ['upload']
var glob = require('glob')
var files = glob.sync(path.resolve(__dirname, '../src/*/index.js'));
var plugins = [];
files.forEach(function(f) {
    var name = /.*/(.*?/index).js/.exec(f)[1]; //register/main这样的文件名
    var c = false;
    for (let f = 0; f < fillter.length; f  ) {
        const element = fillter[f];
        if (name.indexOf(element) > -1) {
            c = true;
            break;
        }
    }
    if (!c) {
        var plug = new HtmlWebpackPlugin({
            filename: path.resolve(__dirname, '../public/vue_dist/'   name   '.html'),
            chunks: [name],
            template: path.resolve(__dirname, '../src/index.html'),
            inject: true
        });
        plugins.push(plug);
    }
});
plugins.push(
    new CleanWebpackPlugin(['vue_dist'], {
        // Absolute path to your webpack root folder (paths appended to this)
        // Default: root of your package
        root: path.resolve(__dirname, '../public/'),

        // Write logs to console.
        verbose: true,

        // Use boolean "true" to test/emulate delete. (will not remove files).
        // Default: false - remove files
        dry: false,

        // If true, remove files on recompile. 
        // Default: false
        watch: false,

        // Instead of removing whole path recursively,
        // remove all path's content with exclusion of provided immediate children.
        // Good for not removing shared files from build directories.
        exclude: ['files', 'to', 'ignore'],

        // allow the plugin to clean folders outside of the webpack root.
        // Default: false - don't allow clean folder outside of the webpack root
        allowExternal: false,

        // perform clean just before files are emitted to the output dir
        // Default: false
        beforeEmit: false
    })
)
module.exports = merge(common, {
    devtool: '#eval-source-map',
    plugins: plugins
});

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map'
        // http://vue-loader.vuejs.org/en/workflow/production.html
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        })
    ])
}

安装成功后,再安装所有依赖


npm install

用到的插件:

运行

CleanWebpackPlugin 删除目录专用

开发环境:

HtmlWebpackPlugin Plugin that simplifies creation of HTML files to serve your bundles

首次运行需要执行init命令生成html入口文件,以后不用再执行

webpack-merge 合并webpack.config 文件

npm run init

glob 找到匹配的文件

然后执行dev,本地环境就可以跑起来了,默认端口是8080,如果有冲突请先kill

ManifestPlugin Webpack plugin for generating asset manifests. 生成打包列表like this

npm run dev

{
"register/index.js": "/vue_dist/register/index.js",
"register/index.js.map": "/vue_dist/register/index.js.map",
"upload/index.js": "/vue_dist/upload/index.js",
"upload/index.js.map": "/vue_dist/upload/index.js.map",
"vendor.js": "/vue_dist/vendor.js",
"vendor.js.map": "/vue_dist/vendor.js.map",
"element-icons.ttf": "/vue_dist/6f0a76321d30f3c8120915e57f7bd77e.ttf",
"glyphicons-halflings-regular.woff2": "/vue_dist/448c34a56d699c29117adc64c43affeb.woff2",
"glyphicons-halflings-regular.woff": "/vue_dist/fa2772327f55d8198301fdb8bcfc8158.woff",
"glyphicons-halflings-regular.ttf": "/vue_dist/e18bbf611f2a2e43afc071aa2f4e1512.ttf",
"glyphicons-halflings-regular.svg": "/vue_dist/89889688147bd7575d6327160d64e760.svg",
"glyphicons-halflings-regular.eot": "/vue_dist/f4769f9bdb7466be65088239c12046d1.eot"
}

在浏览器访问http://127.0.0.1:8080,如果现实下图就说明已经成功了:

expose-loader 解决全局变量的问题 like jQuery 和 $ 对应

生产环境:

本文由皇牌天下投注网发布于计算机教程,转载请注明出处:Vue Webpack开发可复用的单页面富应用教程(配置篇

关键词:

上一篇:js弹窗 js弹出DIV,并使整个页面背景变暗

下一篇:没有了

最火资讯