Skip to content

webpack-externals外部扩展 #53

Open
@conan1992

Description

@conan1992

目的:减小生产环境中项目体积

将第三方的类库放到CDN上,能够大幅度减少生产环境中的项目体积,另外CDN能够实时地根据网络流量和各节点的连接、负载状况以及到用户的距离和响应时间等综合信息将用户的请求重新导向离用户最近的服务节点上
webpack.config.js添加配置

+ externals: {
+       "jquery": "jQuery"
+   }

解释

  • 属性名称jquery表示应该排除 import $ from 'jquery' 中的 jquery 模块,为了替换这个模块,jQuery 的值将被用来检索一个全局的 jQuery 变量。换句话说,当设置为一个字符串时,它将被视为全局的(定义在上面和下面)。
  • index.html中引入cdn;用到html-webpack-plugin;
    webpack.config.js
const path = require("path")
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const Webpack = require("webpack");
module.exports = {
    entry: path.join(__dirname, "src/main.js"),
    output: {
        path: path.join(__dirname, "dist"),
        filename: "bundle.js"
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            title: "布加拉提",
            template: "public/index.html",
            cdn: ["https://code.jquery.com/jquery-3.1.0.js"]
        }),
        new Webpack.NamedModulesPlugin(),
        new Webpack.HotModuleReplacementPlugin()
    ],
    devServer: {
        contentBase: "./dist",
        hot: true
    },
    module: {
        rules: [{
            test: /.vue$/,
            loader: "vue-loader"
        },{
            test: /.css$/,
            use: ["style-loader", "css-loader"]
        }]
    },
    externals: {
        "jquery": "jQuery"
    }
}

templete

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>呵呵</title>
</head>
<body>
    <div id="a">
        <div id="app"></div>
    </div>
    <% htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.forEach( cdn => {%>
        <script src="<%=cdn %>"></script>
    <%}) %>
</body>
</html>

注:

  • plugins中的HtmlWebpackPlugin配置中的cdn是我们要引入的cdn地址;
  • templete中去获取cdn列表循环加载

参考

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions