webpack优化环境配置 - 27.externals(排除依赖)

externals 配置选项提供了「从输出的 bundle 中排除依赖」的方法。

防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。

这里是排除 jQuery的打包。

 

 

1.文件结构

 

 

 

2.代码

 index.js

import $ from 'jquery'

console.log($)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 id="title">hello html</h1>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>

</body>
</html>

webpack.config.js

const {resolve} = require('path')
const HtmlWebpackPlugins = require('html-webpack-plugin')
module.exports = {
    entry: './src/js/index.js',
    output: {
        filename: "js/built.js",
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: []
    },
    plugins: [
        new HtmlWebpackPlugins({
            template: './src/index.html'
        })
    ],
    mode: 'production',
    // externals 配置选项提供了「从输出的 bundle 中排除依赖」的方法。
    // 防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。
    externals: {
        // 拒绝 jQuery 被打包进来
        // jquery: 'jQuery|jquery'
        jquery: 'jQuery'
    }
}

 

3.打包

$ webpack

 

 

 

 

参考文档:https://webpack.docschina.org/configuration/externals/

end~

posted @ 2022-09-09 10:41  Evengod  阅读(577)  评论(0编辑  收藏  举报