Nest: Bundle generated by Webpack throws: Please, make sure to install this library ($ npm install class-validator)

Created on 19 Dec 2018  路  14Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I want developers to pay more attention at issue with Webpack described by several people at the end of the #533 thread.

In short: I copied cats sample project, configured Webpack, but resulting bundle fails with this exception:

[Nest] 14948 - 12/19/2018, 8:52:38 PM [PackageLoader] The "class-validator" package is missing. Please, make sure to install this library ($ npm install class-validator) to take advantage of ValidationPipe. +2ms

To give more information about problem needed for bug reproducing (Webpack config, environment info) I'll just copy here message from thread mentioned above:

https://github.com/nestjs/nest/issues/533#issuecomment-424746662

Has one of you experienced the following error when running a webpack'ed bundle?

[Nest] 23911 - 9/26/2018, 4:41:17 PM [PackageLoader] The "class-transformer" package is missing. Please, make sure to install this library ($ npm install class-transformer) to take advantage of ValidationPipe.

Of course, class-transformer is present in package.json and is installed under node_modules (It is not missing on the disk).
The application can also be run with npm run start or npm run start:prod, so it's really just webpack that is ignoring class-transformer for some reason.

My webpack.conf.js file:

> const path = require('path');
> 
> module.exports = {
>   entry: './dist/main.js',
>   mode: 'production',
>   target: 'node',
>   node: {
>     __dirname: false,
>     __filename: false,
>   },
>   output: {
>     path: path.resolve(__dirname, 'webpack-dist'),
>     filename: 'server.bundle.js',
>   },
> };

Webpack in package.json:

>     "webpack": "^4.20.2",
>     "webpack-cli": "^3.1.1",
>     "webpack-node-externals": "^1.7.2"

My system:

> [System Information]

> OS Version     : Linux 4.9
> NodeJS Version : v10.11.0
> NPM Version    : 6.4.1
> [Nest Information]
> mongoose version : 5.2.2
> common version   : 5.3.9
> core version     : 5.3.10

Any ideas?

Expected behavior

Should not throw such exception

Minimal reproduction of the problem with instructions


Look at quote above from other thread.

Environment

I'm experiencing same issue with following setup:


Nest version: 5.5.0

For Tooling issues:

  • Node version: 10.14.2
  • Platform: Windows
build question 馃檶

Most helpful comment

Can we reopen this? It's not fixed for me in 6.0.5.

All 14 comments

Any solution or workaround on this?

Sorry for being impatient, but this really stops me from using Nest. I want to have comfortable development experience using Webpacks's HotModuleReplacementPlugin like explained in this official tutorial: https://docs.nestjs.com/techniques/hot-reload

People complaining about loadPkg function:

class-validator is loaded by loadPkg function in validation.pipe.js:

classValidator = loadPkg('class-validator');

That's why webpack cant resolve class-validator. Does anyone have a good solution?

Any solution or workaround on this?

Sorry for being impatient, but this really stops me from using Nest. I want to have comfortable development experience using Webpacks's HotModuleReplacementPlugin like explained in this official tutorial: https://docs.nestjs.com/techniques/hot-reload

People complaining about loadPkg function:

class-validator is loaded by loadPkg function in validation.pipe.js:
classValidator = loadPkg('class-validator');
That's why webpack cant resolve class-validator. Does anyone have a good solution?

is your case because of absence of class-validator package? if so you can install by
npm i --save class-validator class-transformer

:) thanks for advice, But first thing I tried is to install different versions of both packages (first time I installed actual packages [_current version_], then I tried to install explicitly versions of packages mentioned in official tutorials: cats app and Webpack example) . But still problem didn't gone.

As I mentioned before: I think people is right and problem is deeper - probably it related to framework's specific way of loading packages (Nest's custom method loadPkg) and Webpack,

Hey,
I have the same issue, but with the fastify package. We use the FastifyAdapter and if I build with webpack, I got the error "[PackageLoader] The "fastify" package is missing. Please, make sure to install this library ($ npm install fastify) to take advantage of FastifyAdapter."
Anyone has a solution to this?

We found a solution to this. If you have a look at the not minified webpack generated js code you will find something like this:

function loadPackage(packageName, context) {
    try {
        return __webpack_require__(149)(packageName);
    }
    catch (e) {
        logger.error(MISSING_REQUIRED_DEPENDENCY(packageName, context));
        process.exit(1);
    }
}

This is causing the thrown error. So we dive deeper in the __webpack_require__(149). The number should be different for you but you can easily search for it. It should only be visible one more time in the js code.

/* 149 */
/***/ (function(module, exports) {

function webpackEmptyContext(req) {
    var e = new Error("Cannot find module '" + req + "'");
    e.code = 'MODULE_NOT_FOUND';
    throw e;
}
webpackEmptyContext.keys = function() { return []; };
webpackEmptyContext.resolve = webpackEmptyContext;
module.exports = webpackEmptyContext;
webpackEmptyContext.id = 149;

/***/ }),

Webpack per default replaces all require() calls with it's own logic like above.
The nestjs code contains a require call which is dynamic so webpack is not able to resolve it at compile time but still replaces it. (https://github.com/nestjs/nest/blob/master/packages/common/utils/load-package.util.ts)

So for the solution we have to tell webpack to just skip this require call and let the application do the normal nodejs require stuff, like traversing node_module folders.

To do this, you npm i string-replace-loader which is a plugin for webpack. Inside your webpack config you add the following under module.rules[]:

{
    test: /load-package\.util\.js$/,
    loader: "string-replace-loader",
    options: {
        search: "require[(]([^'\"])",
        replace: "__non_webpack_require__($1",
        flags: "g",
    },
},

The js code now looks like the following and works:

function loadPackage(packageName, context) {
    try {
        return require(packageName);
    }
    catch (e) {
        logger.error(MISSING_REQUIRED_DEPENDENCY(packageName, context));
        process.exit(1);
    }
}

If you have more files where you dynamically require libs, you have to add them to the regex.
s. https://www.npmjs.com/package/string-replace-loader

It should be fixed in 6.0.0

Can we reopen this? It's not fixed for me in 6.0.5.

i have

"@nestjs/common": {
      "version": "6.2.2",
[Nest] 14640   - 2019-05-24 02:04   [PackageLoader] The "class-transformer" package is missing. Please, make sure to install this library ($ npm install class-transformer) to take advantage of ValidationPipe. +4ms
[0] [nodemon] app crashed - waiting for file changes before starting...



md5-6485f05c6d91bd8f8ac2fdb9241cc41f



npm i class-transformer --save

It's not an issue. class-transformer is and will always be required if you use ValidationPipe

@kamilmysliwiec actually this __is__ an issue. I've created empty project and trying to bundle it using webpack. I get class-transformer errors as well as many others

I'm getting this error on the current version, even when already installed class-validator.

Can you try my solution from above?
s. https://github.com/nestjs/nest/issues/1386#issuecomment-461914216
It should also work in version 6.x, but I don't tested it.

If this works it maybe will be a good idea to put a hint in the docs how to solve this problem.

I'm getting that same issue on a mono-repo project when trying to import libraries that use class-validator into an app. Any suggestion how to overcome that error in a nest mono-repo project?

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

menme95 picture menme95  路  3Comments

cojack picture cojack  路  3Comments

anyx picture anyx  路  3Comments

KamGor picture KamGor  路  3Comments

thohoh picture thohoh  路  3Comments