Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

webpack5 的 SplitChunksPlugin 插件无法将 js 分离问题

官方提到:

SplitChunksPlugin
插件可以将公共的依赖模块提取到已有的入口 chunk 中,或者提取到一个新生成的 chunk。

我写了一个 demo 项目,目录结构如下:
image.png

webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: {
    index: { import: './src/index.js' },
    another: { import: './src/another-module.js' },
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '开发环境',
    })
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  // 分离代码
  optimization: {
    splitChunks: {
      chunks: 'all',
    }
  }
}

index.js

import _ from 'lodash'
import printMe from './print.js'

function component() {
  const element = document.createElement('div');
  const btn = document.createElement('button')

  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  btn.innerHTML = '点击这里,然后查看 console !'
  btn.onclick = printMe

  element.appendChild(btn)

  return element;
}

document.body.appendChild(component());

another-module.js

import _ from 'lodash'
import printMe from './print.js'

console.log(
  _.join(['Another', 'module', 'loaded!'], '')
)

print.js

console.log(123)
export default function printMe() {
  console.log('I get called from print.js!')
}

打包后
image.png

很明显,index.js 和 another-module.js 都引入的 lodash 模块被提取出来了,变为 vendors-node_modules_lodash_lodash_js.bundle.js 文件,但是为什么 index.js 和 another-module.js 都引入的 print.js 没有被提取出来,当我运行项目时,print.js 里的 console.log(123) 明显执行了两次。这是因为 print.js 不是 node_modules 里导致的吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
cacheGroups: {
        defaultVendors: {
          test: /[/]node_modules[/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }

默认规则对node_modules内的模块进行提取,所以print.js是不会被提取进去的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...