| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292 | const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const glob = require("glob");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const CopyWebpackPlugin = require("copy-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const packageJson = require("./../package.json");
const HappyPack = require('happypack');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({size: os.cpus().length});
let pathVars = require("./pathVars");
const { log } = require('console');
let config = {};
/*----------------------------------- page ---------------------------------*/
//测试页面
let files = [].concat(
    glob.sync(pathVars.testPath + `/echarts/Custom*/index.html`),
);
console.log("测试页面\n", files);
let entryDev = {
    vendor: Object.keys(packageJson.dependencies)
};
let pageAry = [];
files.forEach(function (filePath) {
    let tempAry = filePath.split('/');
    //demo文件夹名
    let typeName = tempAry[tempAry.length - 3];
    let chunkName = tempAry[tempAry.length - 2];
    let htmlName = chunkName + "/index.html";
    let obj = {};
    obj["filePath"] = filePath;
    obj["chunkName"] = chunkName;
    obj["htmlName"] = htmlName;
    obj["entryJs"] = pathVars.testPath + "/" + typeName +'/'+chunkName + "/index.js";
    entryDev[chunkName] = obj["entryJs"];
    pageAry.push(obj);
});
//图表主js文件
let chartFiles = glob.sync(pathVars.srcPath + "/chart/echarts/Custom*/Custom*.js");
console.log("图表主js文件\n", chartFiles);
let chartAry = [];
let entryDist = {};
chartFiles.forEach(function (filePath) {
    let tempAry = filePath.split('/');
    let chunkName = tempAry[tempAry.length - 2];
    let obj = {};
    obj["chunkName"] = chunkName;
    chartAry.push(obj);
    //
    entryDist[chunkName] = filePath;
});
/*-----------------------------  entry  ------------------------------*/
config["entryDev"] = entryDev;
config["entryDist"] = entryDist;
/*-----------------------------  devServer  ------------------------------*/
let devServer = {
    // open: true,
    publicPath: "/",
    contentBase: pathVars.devPath,
    hot: true,
    inline: true,
    port: 3000,
    host: 'localhost',
    watchOptions:{
        ignored:/node_modules/,
        aggregateTimeout:500
    }
};
config["devServer"] = devServer;
/*-----------------------------  output  ------------------------------*/
let outputDev = {
    path: pathVars.distPath,
    publicPath: "/",     // 表示资源的发布地址,当配置过该属性后,打包文件中所有通过相对路径引用的资源都会被配置的路径所替换(如:css中背景图的路径)
    filename: "[name]/main.js"
};
config["outputDev"] = outputDev;
let outputDist = {
    path: pathVars.distPath,
    publicPath: "/",
    filename: "[name]_[chunkhash:5].js",
    library: "[name]",
    libraryTarget: "umd"
//  libraryExport: "default"
};
config["outputDist"] = outputDist;
/*-----------------------------  externals  ------------------------------*/
if (process.env.NODE_ENV === "noThird") {
    console.log("==================", process.env.NODE_ENV);
    config["externals"] = {
        'three': {
            commonjs: 'THREE',
            commonjs2: 'THREE',
            amd: 'THREE',
            root: 'THREE'
        },
        'zrender': {
            commonjs: 'zrender',
            commonjs2: 'zrender',
            amd: 'zrender',
            root: 'zrender'
        },
        'gsap': {
            commonjs: 'gsap',
            commonjs2: 'gsap',
            amd: 'gsap',
            root: 'gsap'
        },
        'echarts': {
            commonjs: 'echarts',
            commonjs2: 'echarts',
            amd: 'echarts',
            root: 'echarts'
        }
    };
} else {
    config["externals"] = {};
    config["outputDist"]["filename"]="[name].js"
}
let resolve = {
    alias: {
        utils: path.resolve(__dirname, '../src/utils/'),
    }
};
config["resolve"] = resolve;
/*-----------------------------  module  ------------------------------*/
let rules = [
    {
        test: /\.js$/,
        // exclude: pathVars.nodeModulesPath,
        loader: "babel-loader",
    },
    {
        test: /\.(glsl|vs|fs|vert|frag)$/,
        // exclude: [pathVars.nodeModulesPath, pathVars.dllPath],
        use: ["raw-loader", "glslify-loader"]
    }
]
let imgRuleDev = {
    test: /\.(png|jpg|gif)$/,
    use: [
        {
            loader: 'file-loader',
            options: {
                publicPath: '/',
                name: 'imgInChart/[name]_[hash:5].[ext]'
            }
        }
    ]
}
let imgRuleDist = {
    test: /\.(png|jpg|gif)$/,
    use: [
        {
            loader: 'file-loader',
            options: {
                publicPath: '../../static/',
                name: 'imgInChart/[name]_[hash:5].[ext]'
            }
        }
    ]
};
config["moduleBaseDev"] = {rules: rules.concat(imgRuleDev)};
config["moduleBaseDist"] = {rules: rules.concat(imgRuleDist)};
//---------------------------------- plugin -----------------------------------//
let pluginBase = [
    new webpack.DllReferencePlugin({
        context: pathVars.rootPath,
        manifest: require(pathVars.dllPath + '/manifest.json')
    }),
    new HappyPack({
        id: 'babel',
        loaders: ["babel-loader"],
        threadPool: happyThreadPool
    }),
    new webpack.DefinePlugin({
        my_ENV: JSON.stringify(process.env.my_ENV)
    })
];
const htmlBase = [];
pageAry.forEach(function (page) {
    const htmlPlugin = new HtmlWebpackPlugin({
        title: '',
        template: page["filePath"],
        filename: page["htmlName"],
        inject: 'body',
        chunks: ["manifest", "vendor", "common", page["chunkName"]],
        chunksSortMode: 'none'
    });
    htmlBase.push(htmlPlugin);
});
//------------------- dev
let pluginsDev = [
    new webpack.HotModuleReplacementPlugin()
];
config["pluginsDev"] = pluginBase.concat(pluginsDev, htmlBase);
//------------------- dist
let pluginDist = [
    new CleanWebpackPlugin(pathVars.distPath,
        {
            root: pathVars.rootPath,
            verbose: true
        }
    ),
    new webpack.NoEmitOnErrorsPlugin(),
];
config["pluginDist"] = pluginBase.concat(pluginDist);
//----------------------------------- optimization  ---------------------------//
config["optimizationDev"] = {
    minimize: false,
    splitChunks: {
        chunks: "all", //initial
        minSize: 30 * 1024, //模块大于30k会被抽离到公共模块 也就是说每个页面的js不会大于30k
        minChunks: 1, //模块出现1次就会被抽离到公共模块
        maxAsyncRequests: 5, //异步模块,一次最多只能被加载5个
        maxInitialRequests: 3, //入口模块最多只能加载3个
        name: true,
        cacheGroups: {
            default: {
                chunks: "all",
                name: "common",
                test: /[\\/]src[\\/]/,
                minChunks: 3,
                priority: -20,
                reuseExistingChunk: true
            },
            vendors: {
                chunks: "all",
                name: "vendor",
                test: /[\\/]node_modules[\\/]/,
                minChunks: 1,
                priority: -10
            }
        }
    },
    runtimeChunk: {
        name: "manifest"
    }
};
//
config["optimizationDist"] = {
    minimize: false,
    minimizer: [
        new UglifyJsPlugin({
            cache: true,
            parallel: true,
            uglifyOptions: {
                warnings: false,
                compress: {
                    // warnings: false,
                    drop_debugger: true,
                    drop_console: true
                }
            }
        }),
        new OptimizeCssAssetsPlugin({})
    ],
    splitChunks: {}
};
module.exports = config;
 |