簡體   English   中英

如何在沒有require語句的情況下使用webpack加載目錄中的所有文件

[英]How to load all files in a directory using webpack without require statements

我在我的應用程序中有大量的 javascript 文件分成 4 個子目錄。 在 grunt 中,我抓取所有這些並將它們編譯成一個文件。 這些文件沒有 module.exports 函數。

我想使用 webpack 並將其分成 4 部分。 我不想手動進入並需要我的所有文件。

我想創建一個插件,在編譯時遍歷目錄樹,然后獲取所有 .js 文件名和路徑,然后需要子目錄中的所有文件並將其添加到輸出中。

我希望將每個目錄中的所有文件編譯成一個模塊,然后我可以從我的入口點文件中要求該模塊,或者包含在http://webpack.github.io/docs/plugins.html提到的資產中。

添加新文件時,我只想將其放入正確的目錄中並知道它將被包含在內。

有沒有辦法用 webpack 或某人編寫的插件來做到這一點?

這就是我為實現這一目標所做的:

function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('./modules/', true, /\.js$/));

在我的應用程序文件中,我最終放置了要求

require.context(
  "./common", // context folder
  true, // include subdirectories
  /.*/ // RegExp
)("./" + expr + "")

這篇文章的禮貌: https : //github.com/webpack/webpack/issues/118

它現在正在添加我的所有文件。 我有一個 html 和 css 加載器,它似乎工作得很好。

一個文件夾中所有文件的映射怎么樣?

// { 
//   './image1.png':  'data:image/png;base64,iVBORw0KGgoAAAANS',
//   './image2.png':  'data:image/png;base64,iVBP7aCASUUASf892',
// }

做這個:

const allFiles = (ctx => {
    let keys = ctx.keys();
    let values = keys.map(ctx);
    return keys.reduce((o, k, i) => { o[k] = values[i]; return o; }, {});
})(require.context('./path/to/folder', true, /.*/));

如何獲取當前文件夾中所有圖像的地圖的示例。

const IMAGES_REGEX = /\.(png|gif|ico|jpg|jpeg)$/;

function mapFiles(context) {
  const keys = context.keys();
  const values = keys.map(context);
  return keys.reduce((accumulator, key, index) => ({
    ...accumulator,
    [key]: values[index],
  }), {});
}

const allImages = mapFiles(require.context('./', true, IMAGES_REGEX));

@splintor 的所有優點(謝謝)。

但這里是我自己的派生版本。

好處:

  • 哪些模塊導出收集在{module_name: exports_obj}對象下。
    • module_name是從其文件名構建的。
    • ...沒有擴展名並用下划線替換斜線(在子目錄掃描的情況下)。
  • 添加了注釋以簡化自定義。
    • 即您可能不想在子目錄中包含文件,例如,如果它們是根級模塊手動需要的。

編輯:如果像我一樣,你確定你的模塊除了(至少在根級別)一個常規的 javascript 對象之外不會返回任何東西,你也可以“掛載”它們復制它們的原始目錄結構(參見代碼(深度版本) )部分)。

代碼(原版):

function requireAll(r) {
    return Object.fromEntries(
        r.keys().map(function(mpath, ...args) {
            const result =  r(mpath, ...args);
            const name = mpath
                .replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
                .replace(/\//g, '_') // Relace '/'s by '_'s
            ;
            return [name, result];
        })
    );
};
const allModules = requireAll(require.context(
    // Any kind of variables cannot be used here
    '@models'  // (Webpack based) path
    , true     // Use subdirectories
    , /\.js$/  // File name pattern
));

例子:

最終console.log(allModules);示例輸出console.log(allModules);

{
  main: { title: 'Webpack Express Playground' },
  views_home: {
    greeting: 'Welcome to Something!!',
    title: 'Webpack Express Playground'
  }
}

目錄樹:

models
├── main.js
└── views
    └── home.js

代碼(深度版):

function jsonSet(target, path, value) {
    let current = target;
    path = [...path]; // Detach
    const item = path.pop();
    path.forEach(function(key) {
        (current[key] || (current[key] = {}));
        current = current[key];
    });
    current[item] = value;
    return target;
};
function requireAll(r) {
    const gather = {};
    r.keys().forEach(function(mpath, ...args) {
        const result =  r(mpath, ...args);
        const path = mpath
            .replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
            .split('/')
        ;
        jsonSet(gather, path, result);
    });
    return gather;
};
const models = requireAll(require.context(
    // Any kind of variables cannot be used here
    '@models'  // (Webpack based) path
    , true     // Use subdirectories
    , /\.js$/  // File name pattern
));

例子:

使用此版本的先前示例的結果:

{
  main: { title: 'Webpack Express Playground' },
  views: {
    home: {
      greeting: 'Welcome to Something!!',
      title: 'Webpack Express Playground'
    }
  }
}

這對我有用:

function requireAll(r) { r.keys().forEach(r); } 

requireAll(require.context('./js/', true, /\.js$/));

注意:這可能需要 ./js/ 子目錄中的 .js 文件遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM