如何使用monorepo(yarnpkg工作区)的webpack

我正在使用纱线工作区 ,其中根目录有一个软件包目录与我所有的回购。 每个回购有其自己的node_modules目录包含其依赖关系。 根node_modules目录包含整个项目的所有开发依赖关系以及所有其他与开发相关的东西,如webpack.config文件。 Webpack使用快速模块重新加载快速服务器包。

我的问题是,如何configurationwebpack外部通过整个项目,而不仅仅是在根目录中排除所有node_modules目录?

在这种情况下, webpack-node-externals似乎不起作用。

错误信息:

WARNING in ./packages/servers/express/node_modules/colors/lib/colors.js 127:29-43 Critical dependency: the request of a dependency is an expression WARNING in ./packages/servers/express/node_modules/express/lib/view.js 79:29-41 Critical dependency: the request of a dependency is an expression 

Webpackconfiguration:

 const webpack = require('webpack'); const path = require('path'); const nodeExternals = require('webpack-node-externals'); const StartServerPlugin = require('start-server-webpack-plugin'); module.exports = { entry: [ 'babel-polyfill', 'webpack/hot/poll?1000', path.join(__dirname, '../packages/servers/express/server/index.js') ], watch: true, target: 'node', externals: [ nodeExternals({ whitelist: ['webpack/hot/poll?1000'] }) ], resolve: { alias: { handlebars: 'handlebars/dist/handlebars.js' } }, module: { rules: [ { test: /\.js?$/, use: 'babel-loader', exclude: /node_modules/ } ] }, plugins: [ new StartServerPlugin('server.js'), new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { BUILD_TARGET: JSON.stringify('server') } }) ], output: { path: path.join(__dirname, '../packages/servers/express/.build'), filename: 'server.js' } }; 

Yarn工作空间将兼容模块提升到根node_modules目录,而将任何不兼容的(不同的semver等)模块与依赖的工作空间的node_modules目录相关联。 如果一个包没有使用相对path而被请求,它可能是来自node_module的原生的,也可能是来自其中一个工作空间的符号链接包。 你可能希望所有这些包是外部的。

如何configurationwebpack外部通过整个项目排除所有node_modules目录,而不仅仅是在根?

我会尝试使用webpack的外部选项的function 。 您传递了require的上下文,请求的模块的名称以及callback,以指示是否将此特定导入(require)视为外部。

 externals: [ (ctx, req, cb) => { if (!/node_modules/.test(ctx) && req[0] !== '.') { // Assumes you have defined an "entries" variable let notAnEntry = (path) => { return Object.keys(entries).every((entry) => { return entries[entry] !== path }); }; if (notAnEntry(require.resolve(req))) { // This module is external in a commonjs context return cb(null, `commonjs ${req}`); } } cb(); } ] 

有关解决方法,请参阅https://github.com/blackxored/elasticdev-starter-kit/blob/master/platforms/server/webpack.server.babel.js

这指示插件使用package.json而不是查找node_modules。

感谢@blackxored,我能够解决它在我的项目。

在您的webpackconfiguration文件中执行以下操作:

 import nodeExternals from 'webpack-node-externals' 

然后加

 externals: [ nodeExternals({ modulesFromFile: true, }), ],