как использовать общий бизнес-код webpack?

Я использую webpack.optimize.CommonsChunkPlugin для создания дополнительного фрагмента (vueCommon.js), который содержит vuejs, vue-router, vue-resource...; но я хочу создать еще один бизнес-общий фрагмент, такой как util.js. Они используются только в некоторые страницы "импортировать ajax из '../service/service.js'";

проблемы после сборки: каждый сгенерированный page.js имеет код service.js。

краткие демонстрации: https://github.com/wxungang/vueJs

//webpack.base.js

"use strict";

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

const CONFIG = require('./config');
var projectRoot = CONFIG.projectRoot || path.resolve(__dirname, '../');
var _ENV = CONFIG.env || 'dev';//prod

module.exports = {
    devtool: _ENV != 'prod' ? '#eval-source-map' : false,
    context: __dirname,//http://wxungang.github.io/1104/vue
    entry: {
        app: path.join(projectRoot, './vue/app.js'),
        page: path.join(projectRoot, './vue/page.js')
    },
    output: {
        path: path.join(projectRoot, './build/vue-' + _ENV),
        publicPath: '',//'./build/vue-'+_ENV+'/',//path.join(__dirname, '../src/build/dev/')
        filename: '[name].js',
        chunkFilename: 'chunks/[name].chunk.js',
        // crossOriginLoading: 'anonymous'
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.common.js',
            'vue-router$': 'vue-router/dist/vue-router.common.js'
        },
        modules: ["node_modules"],
        mainFiles: ["index", "app"],
        extensions: [".js", ".json", '.vue']
    },
    module: {
        rules: [
            {
                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 nessessary.
                        'scss': 'vue-style-loader!css-loader!sass-loader',
                        'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
                        'less': 'vue-style-loader!css-loader!less-loader'
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.less$/,
                loader: "style-loader!css-loader!less-loader"
            },
            {
                test: /\.scss$/,
                loaders: ["style-loader", "css-loader", "sass-loader"]
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            },
            {
                test: /\.html$/,
                loader: 'vue-html-loader'
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    plugins: [
        //注入一些全局变量
        new webpack.DefinePlugin({
            _ENV_: _ENV,
            _VERSION_: JSON.stringify("1.0.0")
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "commons",
            // (the commons chunk name)

            filename: "vueCommons.js",
            // (the filename of the commons chunk)

            // minChunks: 2,
            // (Modules must be shared between 3 entries)

            // chunks: ["pageA", "pageB"],
            // (Only use these entries)
            // children: true,
            // async: true,
        }),
        //可以和entry文件联合配置
        new HtmlWebpackPlugin({
            inject: false,
            title: 'vueJs of app',
            filename: 'app.html',
            template: '../vue/entry/template.ejs',
            scripts: ['./vueCommons.js', './app.js']
        }),
        new HtmlWebpackPlugin({
            inject: false,
            title: 'vueJs of page',
            filename: 'page.html',
            template: '../vue/entry/template.ejs',
            scripts: ['./vueCommons.js', './page.js']
        })
    ]

};


person daidaibenben    schedule 10.02.2017    source источник
comment
Не могли бы вы предоставить свой webpack.config.js? Трудно себе это представить.   -  person ickyrr    schedule 10.02.2017


Ответы (1)


Как вы использовали CommonsChunkPlugin для создания vueCommon.js?

Простой способ — добавить новую запись в wepack, например

utils: ['../service/service.js']

затем добавьте новый экземпляр CommonsChunkPlugin в массив плагинов веб-пакета, подобный этому

new webpack.optimize.CommonsChunkPlugin('utils'),

CommonsChunkPlugin сделает всю работу, удалив все модули utils в других файлах фрагментов и сгенерировав только один utils.js.

Или вы можете просто установить параметр minChunks существующего плагина CommonsChunkPlugin в число, чтобы объединить файл vue и утилиты.

person icewind    schedule 10.02.2017