当我们希望使用CDN来引入jquery时,就不需要在打包时将jQuery打包。
-
配置webpack配置文件webpack.config.js,添加externals配置
const path = require('path'); const { CleanWebpackPlugin} = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'production', entry: './src/js/index.js', output: { filename: 'js/[name][contenthash:8].js', path: path.resolve(__dirname, 'bulid'), }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], externals: { //不打包jquery文件 jquery: 'jQuery' } }
-
在入口文件index.js中引入jquery
import $ from 'jquery' $('#btn').on('click', function (){ console.log('click'); })
-
在模板文件index.html中使用cdn加载jquery
<button id="btn">按钮</button> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
-
打包
webpack
-
在打包信息中可以看到打包后的文件非常小