如何在webpack的入口中添加通配符映射

我需要将脚本文件夹中的所有js文件全部包装好。我试过了

module.exports = { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader"], } ], }, entry: "./src/scripts/*.js", output: { path: './src/build', filename: '[name].js' } }; 

我得到这样的错误,

 ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory' ./s rc/scripts/* in E:\Web project\ReactJS\react-tutorial resolve file E:\Web project\ReactJS\react-tutorial\src\scripts\* doesn't exist E:\Web project\ReactJS\react-tutorial\src\scripts\*.webpack.js doesn't exist E:\Web project\ReactJS\react-tutorial\src\scripts\*.web.js doesn't exist E:\Web project\ReactJS\react-tutorial\src\scripts\*.js doesn't exist E:\Web project\ReactJS\react-tutorial\src\scripts\*.json doesn't exist resolve directory E:\Web project\ReactJS\react-tutorial\src\scripts\* doesn't exist (directory d efault file) E:\Web project\ReactJS\react-tutorial\src\scripts\*\package.json doesn't exist (directory description file) 

它不是search所有的js文件,而是正在寻找* .js这样的。帮我把我所错过的

entry值应parsing为特定文件或特定文件的列表。

从webpack文档 :

如果你传递一个string:该stringparsing为一个启动时加载的模块。

如果传递数组:所有模块在启动时加载。 最后一个是导出。

如果您只是试图定义一个模块,请编辑您的entry值以指向您的主应用程序文件,然后需要其他模块。

如果你真的想捆绑目录中的所有文件,请参阅arseniews的答案

拥有一个或几个入口点对于大多数用例来说应该是足够的,但是如果您真的想要捆绑目录中的所有文件,则可以使用以下命令:

正如这里所解释的: https : //github.com/webpack/webpack/issues/370

 var glob = require("glob"); // ... entry: glob.sync("./src/scripts/*.js") 

Webpack期待entryconfiguration的文件列表 ,而不是glob模式 。

您必须手动列出文件,或者自动使用此代码段

 var fs = require('fs'), entries = fs.readdirSync('./src/scripts/').filter(function(file) { return file.match(/.*\.js$/); }); 

然后传递给webpack的configuration。

我在Webpack 2.4.1中有一些文件path的问题,所以做了这个。

 const HtmlWebpackPlugin = require('html-webpack-plugin'); const fs = require('fs'); function getEntries (){ return fs.readdirSync('./src/pages/') .filter( (file) => file.match(/.*\.js$/) ) .map((file) => { return { name: file.substring(0, file.length - 3), path: './pages/' + file } }).reduce((memo, file) => { memo[file.name] = file.path return memo; }, {}) } const config = { entry: getEntries, output: { path: resolve('./public'), filename: '[name].js' }, plugins: [ new HtmlWebpackPlugin({ title: 'My App', filename: '[name].html', template: './pages/_template.html' }) ] } 

只使用glob.sync会导致连续的文件名,例如0.[hash].js1.[hash].js ,因为entry需要一个对象,其中包含该文件在关键字中的名称及其在该值中的位置,但glob.sync返回一个数组。

以下方法的好处是可以根据文件名生成具有键和值的对象,还可以添加其他条目,例如vendorcommon 。 需要lodash。

 const glob = require("glob"); const _ = require('lodash'); module.exports = { entry: Object.assign({}, _.reduce(glob.sync("./src/*.js"), (obj, val) => { const filenameRegex = /([\w\d_-]*)\.?[^\\\/]*$/i; obj[val.match(filenameRegex)[1]] = val; return obj; }, {}), { vendor: [ 'lodash' ] } ), output: { filename: '[name].[chunkhash].bundle.js', path: path.resolve(__dirname, 'dist') } } 

后者将生成以下对象并将其传递给entry ,前提是我们在./src目录中有index.jsapp.js

 { index: './src/index.js', app: './src/app.js', vendor: [ 'lodash' ] }