具有动态条目的Webpack

我正在尝试通过webpack动态加载JS文件,以便更轻松地添加whitelabel客户。目前,我必须不断更新webpack配置以每次手动添加其文件,但是我想将此设置为动态方法,这样我就可以在需要时添加JS文件,而不必担心webpack。

我在webpack.config.js中的脚本

var Encore = require('@symfony/webpack-encore');
var webpack = require('webpack');
var DelWebpackPlugin = require('del-webpack-plugin');
var fs = require('fs');

 //This is how we used to do it before we implemented whitelabels.
 Encore
     .setOutputPath('web/build/')
     .setPublicPath('/build')
     .enableVersioning()

     .autoProvideVariables({
         $: 'jquery',jQuery: 'jquery','window.jQuery': 'jquery'
        })

     .addPlugin(new DelWebpackPlugin({
         info: true,include: ['**.*']
     }))

     .addEntry('app','./assets/app/js/global.js')
     .addEntry('client1','./assets/app/js/whitelabels/client1.js')
     .addEntry('client2','./assets/app/js/whitelabels/client2.js')

     .enableSassLoader()

     .enableSourceMaps(!Encore.isProduction())
 ;
  module.exports = Encore.getWebpackConfig();

每个客户端在文件夹whitelabels中都有自己的js。我的目标是不必在每次添加新的whitelabel客户时都维护webpack配置。

下面是我尝试动态加载文件时的尝试。

var whitelabels = './assets/app/js/whitelabels';
var list = [];

fs.readdir(whitelabels,function(err,items) {
    items.forEach(item => {

        Encore
            .setOutputPath('web/build/')
            .setPublicPath('/build')
            .enableVersioning()
            .autoProvideVariables({
                $: 'jquery','window.jQuery': 'jquery'
            })
            .addPlugin(new DelWebpackPlugin({
                info: true,include: ['**.*']
            }))
            .addEntry(item.replace('.js',''),'./assets/app/js/whitelabels/'+ item)
            .enableSassLoader()
            .enableSourceMaps(!Encore.isProduction());

        const otherConfigs = Encore.getWebpackConfig();
        otherConfigs.name = item;
        list.push(otherConfigs);
        Encore.reset();
    })
});
// export the final configuration
module.exports = list;

但是无论我尝试什么,它总是会给我以下错误

Running webpack ...

/Volumes/git/project/node_modules/webpack/bin/webpack.js:212
            outputOptions.context = firstOptions.context;
                                                 ^

TypeError: Cannot read property 'context' of undefined
    at processOptions (/Volumes/git/project/node_modules/webpack/bin/webpack.js:212:41)
    at yargs.parse (/Volumes/git/project/node_modules/webpack/bin/webpack.js:397:2)
    at Object.Yargs.self.parse (/Volumes/git/project/node_modules/yargs/yargs.js:533:18)
    at Object.<anonymous> (/Volumes/git/project/node_modules/webpack/bin/webpack.js:152:7)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
error Command failed with exit code 1.

Encore.getWebpackConfig()的转储;

{ context: '/Volumes/git/project',entry:
   { 
     app: './assets/app/js/global.js',client1: './assets/app/js/whitelabels/client1.js',client2: './assets/app/js/whitelabels/client2.js' },output:
   { path: '/Volumes/git/project/web/build',filename: '[name].[chunkhash:8].js',publicPath: '/build/',pathinfo: true },module: { rules: [ [Object],[Object],[Object] ] },plugins:
   [ ExtractTextPlugin {
       filename: '[name].[contenthash:8].css',id: 2,options: [Object] },DeleteUnusedEntriesJSPlugin { entriesToDelete: [] },ManifestPlugin { opts: [Object] },LoaderOptionsPlugin { options: [Object] },NamedmodulesPlugin { options: {} },WebpackChunkHash {
       algorithm: 'md5',digest: 'hex',additionalHashContent: [Function] },ProvidePlugin { definitions: [Object] },DefinePlugin { definitions: [Object] },FriendlyErrorsWebpackPlugin {
       compilationSuccessInfo: [Object],onErrors: undefined,shouldClearConsole: false,formatters: [Array],transformers: [Array] },AssetOutputDisplayPlugin { outputPath: 'web/build',friendlyErrorsPlugin: [Object] },DelWebpackPlugin { options: [Object] } ],devtool: 'inline-source-map',performance: { hints: false },stats:
   { hash: false,version: false,timings: false,assets: false,chunks: false,maxModules: 0,modules: false,reasons: false,children: false,source: false,errors: false,errorDetails: false,warnings: false,publicPath: false },resolve:
   { extensions: [ '.js','.jsx','.vue','.ts','.tsx' ],alias: {} },externals: {} }
woai0108 回答:具有动态条目的Webpack

这可能有效

var Encore = require("@symfony/webpack-encore");
var webpack = require("webpack");
var DelWebpackPlugin = require("del-webpack-plugin");
var fs = require("fs");

var whitelabels = "./assets/app/js/whitelabels";

Encore
  .setOutputPath("web/build/")
  .setPublicPath("/build")
  .enableVersioning()
  .autoProvideVariables({
    $: "jquery",jQuery: "jquery","window.jQuery": "jquery"
  })
  .addPlugin(
    new DelWebpackPlugin({
      info: true,include: ["**.*"]
    })
  )
  .addEntry("app","./assets/app/js/global.js");

fs.readdir(whitelabels,function(err,items) {
  items.forEach(item => {
    Encore.addEntry(item.replace(".js",""),"./assets/app/js/whitelabels/" + item)
  });
});

Encore
  .enableSassLoader()
  .enableSourceMaps(!Encore.isProduction());

module.exports = Encore.getWebpackConfig();
,

你必须使用同步方法。

  var whitelabels = "./assets/app/js/whitelabels";
  var items=fs.readdirSync(whitelabels);
  items.forEach(item => {
       Encore.addEntry(item.replace(".js","./assets/app/js/whitelabels/" + item)
  });
,

我是这样做的 - 您必须调整 glob 模式和路径以满足您的需求。 “chalk”插件不是必需的,你可以删除它 - 我添加它是为了更好的输出。

关键是,您必须同步添加它(如本例中的 glob.sync)。

const chalk = require('chalk');
const glob = require("glob");
const path = require('path');

// add all components recursively as Encore entry
const entryPoints = glob.sync('**/index.js',{
  'cwd': './your/entrypoints/folder'
});

entryPoints.forEach((file) => {
  const filePath = './your/entrypoints/folder/' + file;
  const name = file.replace(/\/index\.js/,'');
  console.log(`adding entry ${chalk.green(name)} located at ${chalk.green(filePath)}`);
  Encore.addEntry(name,filePath);
});
本文链接:https://www.f2er.com/2979087.html

大家都在问