node.js - 使用 Webpack 捆绑 Sqlite3 导致编译错误

标签 node.js typescript sqlite webpack

我刚刚将 Sqlite3 作为依赖项添加到我的项目(在服务器端),当我尝试捆绑服务器代码以在生产中部署时,webpack 现在会生成一些错误。

WARNING in ./node_modules/node-pre-gyp/lib/util/compile.js 39:27-49
Module not found: Error: Can't resolve 'npm' in 'C:\git\server\node_modules\node-pre-gyp\lib\util'
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./util/compile.js ./util/compile
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-gyp/lib/Find-VS2017.cs 7:6
Module parse failed: Unexpected token (7:6)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| // Usage:
| // powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
> using System;
| using System.Text;
| using System.Runtime.InteropServices;
 @ ./node_modules/node-gyp/lib/ sync ^\.\/.*$ ./Find-VS2017.cs
 @ ./node_modules/node-gyp/lib/node-gyp.js 55:13-36 197:38-55
 @ ./node_modules/node-pre-gyp/lib/util/compile.js 29:28-55
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./util/compile.js ./util/compile
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-gyp/lib/node-gyp.js 67:16-37
Module not found: Error: Can't resolve '../package' in 'C:\git\server\node_modules\node-gyp\lib'
 @ ./node_modules/node-pre-gyp/lib/util/compile.js 29:28-55
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./util/compile.js ./util/compile
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-pre-gyp/lib/info.js 14:14-32
Module not found: Error: Can't resolve 'aws-sdk' in 'C:\git\server\node_modules\node-pre-gyp\lib'
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./info.js ./info
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-pre-gyp/lib/publish.js 18:14-32
Module not found: Error: Can't resolve 'aws-sdk' in 'C:\git\server\node_modules\node-pre-gyp\lib'
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./publish.js ./publish
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-pre-gyp/lib/unpublish.js 16:14-32
Module not found: Error: Can't resolve 'aws-sdk' in 'C:\git\server\node_modules\node-pre-gyp\lib'
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./unpublish.js ./unpublish
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

ERROR in ./node_modules/node-pre-gyp/lib/util/nw-pre-gyp/index.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <!doctype html>
| <html>
| <head>
 @ ./node_modules/node-pre-gyp/lib/ sync ^\.\/.*$ ./util/nw-pre-gyp/index.html
 @ ./node_modules/node-pre-gyp/lib/node-pre-gyp.js 52:13-36 184:38-55
 @ ./node_modules/sqlite3/lib/sqlite3-binding.js 1:13-36
 @ ./node_modules/sqlite3/lib/sqlite3.js 2:14-45
 @ ./src/persistence/SqlLiteDatabase.ts 8:18-36
 @ ./src/messaging/ObjectService.ts 13:26-67
 @ ./src/main.ts 41:24-60

webpack 5.10.0 compiled with 6 errors and 1 warning in 20200 ms

Webpack 配置如下:

const path = require("path");
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const DotEnvPlugin = require('dotenv-webpack');

const WebPackIgnorePlugin =
{
  checkResource: function(resource)
  {
    const lazyImports =
    [
        '@nestjs/microservices',
        '@nestjs/microservices/microservices-module',
        'cache-manager',
        'class-transformer',
        'class-validator',
        'fastify-static',
    ];
  
    if (!lazyImports.includes(resource))
      return false;

    try
    {
      require.resolve(resource);
    }
    catch (err)
    {
      return true;
    }
  
    return false;
  }
};

module.exports =
{
  mode: 'production',
  target: 'node',
  entry:
  {
    server: './src/main.ts',
  },
  devtool: 'source-map',
  module:
  {
    exprContextCritical: false,
    rules:
    [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve:
  {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  node: {
    __dirname: false,
  },
  plugins:
  [
    new CleanWebpackPlugin(),
    new webpack.IgnorePlugin(WebPackIgnorePlugin),
    new DotEnvPlugin({ path: './.env', safe: true }),
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }),
  ],
  optimization:
  {
    minimize: false
  },
  performance:
  {
    maxEntrypointSize: 10 * 1024 * 1024,
    maxAssetSize: 10 * 1024 * 1024
  },
  output:
  {
    filename: '[name].js',
    path: path.resolve(__dirname, 'prod'),
  },
};

配置文件:

{
  "compilerOptions": {
    "incremental": true,                      /* Enable incremental compilation */
    "target": "ES2020",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "sourceMap": true,                        /* Generates corresponding '.map' file. */
    "outDir": "./prod",                       /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "baseUrl": "./",                          /* Base directory to resolve non-absolute module names. */
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "experimentalDecorators": true,           /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,            /* Enables experimental support for emitting type metadata for decorators. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
    "resolveJsonModule": true                 /* Allow importing data from json files. */
  }
}

package.json:

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "private": true,
  "license": "ISC",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "@nestjs/common": "^7.4.2",
    "@nestjs/core": "^7.4.2",
    "@nestjs/passport": "^7.1.0",
    "@nestjs/platform-express": "^7.4.2",
    "@nestjs/platform-ws": "^7.4.2",
    "@nestjs/serve-static": "^2.1.3",
    "@nestjs/websockets": "^7.4.2",
    "client": "file:../client",
    "common": "file:../common",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "encoding-japanese": "^1.0.30",
    "express-session": "^1.17.1",
    "passport": "^0.4.1",
    "passport-custom": "^1.1.1",
    "reflect-metadata": "^0.1.13",
    "sqlite3": "^5.0.0",
    "winston": "^3.3.3",
    "winston-daily-rotate-file": "^4.5.0",
    "ws": "^7.3.1"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.4.1",
    "@nestjs/schematics": "^7.0.1",
    "@nestjs/testing": "^7.4.2",
    "@types/cors": "^2.8.6",
    "@types/encoding-japanese": "^1.0.16",
    "@types/express": "^4.17.6",
    "@types/express-session": "^1.17.0",
    "@types/jest": "^26.0.0",
    "@types/node": "^14.0.13",
    "@types/passport": "^1.0.4",
    "@types/sqlite3": "^3.1.6",
    "@types/supertest": "^2.0.8",
    "@types/ws": "^7.2.6",
    "@typescript-eslint/eslint-plugin": "3.0.2",
    "@typescript-eslint/parser": "3.0.2",
    "bufferutil": "^4.0.1",
    "clean-webpack-plugin": "^3.0.0",
    "copyfiles": "^2.3.0",
    "cross-env": "^7.0.2",
    "dotenv-webpack": "^2.0.0",
    "eslint": "^7.3.0",
    "eslint-config-prettier": "^6.10.0",
    "eslint-plugin-import": "^2.20.1",
    "jest": "26.0.1",
    "json-d-ts": "^1.0.1",
    "prettier": "^1.19.1",
    "supertest": "^4.0.2",
    "ts-jest": "26.1.0",
    "ts-loader": "^6.2.2",
    "ts-node": "^8.10.2",
    "typescript": "^4.0.2",
    "utf-8-validate": "^5.0.2",
    "webpack": "^5.3.2",
    "webpack-cli": "^4.1.0"
  }
}

最佳答案

您只需在 webpack 中将 sqlite3 指定为外部模块,这样它就不会被捆绑/解析。这是必需的,因为它是 native /二进制包。

只需将以下内容添加到您的 webpack 配置中:

externals: {
    sqlite3: 'commonjs sqlite3',
},

包裹webpack-node-externals对所有 node_modules 执行相同的操作也可能会有所帮助。

关于node.js - 使用 Webpack 捆绑 Sqlite3 导致编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65297136/

相关文章:

javascript - 如何扁平化js数组

node.js - 如何使用 Nodejs 在 Express-validator 中验证 multipart/form-data

javascript - 同步 forEach 循环(等待它结束)

javascript - 将 CSS 添加到 EJS

SQLite3 使用 LEFT JOIN 和 UNION 模拟 RIGHT OUTER JOIN

typescript - 转译 Angular2 TS 时如何配置 gulp-typescript 以与 JSPM 一起工作

typescript :函数返回类型取决于输入函数返回类型

typescript - NativeScript 应用程序为 "Error-ReferenceError-ErrorEvent is not defined"

python - 使用 SQlite 在 Python shell 中获取自动 ID

android - 我们如何删除sqlite中的外键?