如果您只需要执行您的模块
您需要entry
在 webpack 配置中设置属性。此属性接受数组作为要包含在包中的文件的值。
// webpack.config.js
const fs = require('fs');
const path = require('path');
const getModulePath = module => path.resolve(__dirname, './relative/path/to/modules/directory', module);
const fileContent = fs.readFileSync('./your.json');
const entries = JSON.parse(fileContent).map(getModulePath);
module.exports = {
// all entries will be built during one build process
// if you need you can split each entry to separate config file
entry: {
bundle1: entries, // build modules from JSON file to single bundle
bundle2: [ './file1', './file2' ], // build static modules to single bundle
bundle3: './sindle/file', // "classic" build
all: [ ...entries, './file1', './file2', './sindle/file' ], // you can combine everything to 1 bundle
},
};
如果您需要从模块中导出某些内容
不幸的是,webpack 作为数组的条目对您没有帮助,因为它只会导出数组中的最后一个文件。
我没有听说过这样的插件可以组合 certan 文件并将其用作入口点。但是您可以自己创建这样的文件。
// webpack.config.js
const fs = require('fs');
const path = require('path');
// saving tmp file location
const pathToCreatedFile = path.resolve(__dirname, './path/to/created/file');
// implement fn to get relative path to modules from tmp file
const getModulePath = module => path.relative(pathToCreatedFile, path.resolve(
__dirname,
'./relative/path/to/modules/directory',
module,
));
// read json
const fileContent = fs.readFileSync('./path/to/your.json');
// prepare modules for tmp file
const entries = JSON.parse(fileContent)
.map(item => ({
name: item.slice(7),
relpath: getModulePath(item),
}));
// here generate import directive for each module. I used `import * as modules_name from 'path';` format
// you can choose any
const importsString = entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n');
// here generate exports from tmp file. It contain of all imports
const exportsString = `export {${entries.map(({name}) => name).join(',\n')}};`;
// and here just concatenate imports ad exports
const content = [
entries.map(({ name, relpath }) => `import * as ${name} from '${relpath}';`).join('\n'),
`export {${entries.map(({name}) => name).join(',\n')}};`,
].join('\n');
// and save tmp file content to fs
fs.writeFileSync(pathToCreatedFile, content);
module.exports = {
// and here use saved tmp file path as entry point
entry: pathToCreatedFile,
};
导入构建的捆绑包后,它将返回带有模块的普通对象。您可以使用Object.values
或类似方法将您的依赖项作为数组。
还有另一种方法,您可以格式化exportString
以导出导入数组。
我使用import * as name from ...
格式向您展示了更常见的创建文件的方法。如果您没有任何默认导出或只有默认导出,最好分别使用export * from ...
或export {default as name} from ...
格式化。