Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack-externals外部扩展 #53

Open
conan1992 opened this issue Jul 24, 2020 · 0 comments
Open

webpack-externals外部扩展 #53

conan1992 opened this issue Jul 24, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

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

将第三方的类库放到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列表循环加载

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant