Разделите блок "вендора" с помощью веб-пакета 2

У меня есть конфигурация разделения кода, похожая на официальную документацию, и все работает отлично - все мои модули узлов находятся в блоке "vendor" (включая "babel-polyfill"). Но теперь мне нужно переместить babel-polyfill и все его зависимости в отдельный чанк ("polyfills"), чтобы иметь возможность загрузить его до моего пакета поставщика. Есть идеи, как это сделать?

Мой конфиг:

...
entry: {
  main: './index.jsx'
},
...
new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
  minChunks: function (module) {
    return module.context && module.context.indexOf('node_modules') !== -1;
  }
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' })
...

1 ответ

Решение

Получить зависимости

Вы можете прочитать package.json от babel-polyfill

const path = require('path');

function getDependencies () {

       // Read dependencies...
       const { dependencies } = require('node_modules/babel-polyfill/package.json');

       // Extract module name
       return Object.keys(dependencies);
}

Просто вызовите его (должен вернуть массив с dependencies):

const dependencies = getDependencies(); // ['module', ...]

Обнаружить полифилы

Проверьте, является ли модуль babel-polyfill или зависимость:

 function isPolyfill(module){

     // Get module name from path
     const name = path.posix.basename(module.context)              

     // If module has a path 
     return name &&

     // If is main module or dependency
     ( name === "babel-polyfill" || dependencies.indexOf(name) !== -1 ); 
 }

Удалять babel-polyfill и зависимости просто проверить, если возвращается false

new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: function (module) {

        // If has path
        return module.context &&

        //If is a node-module
        module.context.indexOf('node_modules')!== -1 &&

        // Remove babel-polyfill and dependencies
        isPolyfill(module) === false;
    }
})

Создайте блок polyfills

Выбрать только babel-polyfill и зависимости просто проверить, если возвращается true

new webpack.optimize.CommonsChunkPlugin({
    name: 'polyfills',

    minChunks: function (module) {

        // If has a path
        return module.context &&

        //If is a node-module
        module.context.indexOf('node_modules')!== -1 &&

        // Select only  babel-polyfill and dependencies
        isPolyfill(module) === true;
    }
})
Другие вопросы по тегам