首页 > 解决方案 > 在 webpack 构建中只包含 jquery slim?

问题描述

如何在我的 webpack 构建中只包含 jquery slim?

现在,我正在包含这样的 jquery,它工作正常,但我不想加载整个库..

webpack.config.js

module.exports = {
...
 module: {
  rules: [
   ...
    {
        test: require.resolve('jquery'),
        use: [{
            loader: 'expose-loader',
            options: 'jQuery'
        },
        {
            loader: 'expose-loader',
            options: '$'
         }]
    }
  ]
  ...
  plugins: [
   new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    })
  ]
 }

}

我在 npm 中找不到官方的 jquery-slim 包,所以我想我的想法是安装整个 jquery 包,并且只使用我想要的东西,但我无法找到如何做到这一点。

标签: javascriptjquerywebpack

解决方案


jquery-slim.jsjquery.
它在node_modules/jquery/dist/jquery-slim.js

所以你需要做的就是将加载器和插件指向jquery.slim.js路径:

module.exports = {
...
 module: {
  rules: [
   ...
    {
        test: require.resolve('jquery/dist/jquery.slim'),
        use: [{
            loader: 'expose-loader',
            options: 'jQuery'
        },
        {
            loader: 'expose-loader',
            options: '$'
         }]
    }
  ]
  ...
  plugins: [
   new webpack.ProvidePlugin({
        $: 'jquery/dist/jquery.slim',
        jQuery: 'jquery/dist/jquery.slim'
    })
  ]
 }

}

推荐阅读