複数のエントリーポイントファイルを持ち、それぞれ別の出力ファイルにバンドルするwebpack.config.jsの例
const path = require('path'); module.exports = { entry: { test1: './src/test1.js', // test1.js をエントリーポイントとして指定 test2: './src/test2.js', // test2.js をエントリーポイントとして指定 }, output: { filename: '[name]_bundle.js', // [name] はエントリーポイントのキーに置換される path: path.resolve(__dirname, 'dist'), // 出力ディレクトリのパス }, module: { rules: [ // ローダーの設定... ], }, };
カスタムローダ、ソース展開
const fs = require('fs'); const path = require('path'); module.exports = function(source) { const callback = this.async(); function expandDSMRequire(content, directory) { return content.replace(/hoge\.require(once)?\(["'](.+?)["']\)/g, (_, requireOnce, requiredFileName) => { const filePath = path.resolve(directory, requiredFileName); const requiredFileContent = fs.readFileSync(filePath, 'utf-8'); const comment = `/* Start: ${requiredFileName} */\n`; const expandedContent = expandDSMRequire(requiredFileContent, path.dirname(filePath)); return comment + expandedContent + `\n/* End: ${requiredFileName} */`; }); } const expandedSource = expandDSMRequire(source, path.dirname(this.resourcePath)); callback(null, expandedSource); };
カスタムローダを使う
const path = require('path'); module.exports = { entry: './src/main.js', // エントリーポイントファイルのパスを指定 output: { filename: 'bundle.js', // バンドルされたファイル名 path: path.resolve(__dirname, 'dist'), // 出力ディレクトリのパス }, module: { rules: [ { test: /\.js$/, // .jsファイルにローダーを適用 exclude: /node_modules/, use: [ 'babel-loader', // 他のローダー(必要に応じて) path.resolve(__dirname, 'path-to-your-loader', 'custom-loader.js'), // カスタムローダーのパスを指定 ], }, ], }, };
const fs = require('fs'); const path = require('path'); module.exports = function(source) { const callback = this.async(); function expandDSMRequire(content, directory) { return content.replace(/hoge\.require(once)?\(["'](.+?)["']\)/g, (_, requireOnce, requiredFileName) => { const filePath = path.resolve(directory, requiredFileName); const requiredFileContent = fs.readFileSync(filePath, 'utf-8'); const comment = `/* Start: ${requiredFileName} */\n`; const expandedContent = expandDSMRequire(requiredFileContent, path.dirname(filePath)); return comment + expandedContent + `\n/* End: ${requiredFileName} */`; }); } function replaceForEachIn(content) { return content.replace(/for each \((.*?) in (.*?)\) {/g, (_, loopVar, collection) => { return `for (var ${loopVar} in ${collection}) {`; }); } const expandedSource = replaceForEachIn(expandDSMRequire(source, path.dirname(this.resourcePath))); callback(null, expandedSource); };
const replacedContent = content.replace(/for each \(.* in .*\) {/g, match => { const variable = match.match(/for each \(.* in (.*)\) {/)[1].trim(); const replacement = match.replace(/for each/, 'for') + ` var _keys = Object.keys(${variable});` + ` for (var _i = 0; _i < _keys.length; _i++) {` + ` var ${variable} = _keys[_i];` + ` var ${variable} = ${variable}[${variable}];`; return replacement; });
npm install --save-dev fs path
npx webpack --config webpack.config.js