ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.33k stars 788 forks source link

crypto is not defined #383

Closed kapitanluffy closed 2 years ago

kapitanluffy commented 2 years ago

image

here's the tsconfig

{
  "compilerOptions": {

    /* Modules */
    "module": "esnext",                                /* Specify what module code is generated. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
  }
}

here's babel

const presets = [
    "@babel/preset-env",
    "@babel/preset-typescript"
];

const config = { presets };

export default config

here's webpack

import path from 'path';
import {fileURLToPath} from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const config = {
  mode: "development",
  output: {
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(tsx?|m?js)$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.json', '.wasm', '.ts', '.jsx', '.tsx']
  },
  watchOptions: {
    ignored: ["**/node_modules"]
  }
}

export default config
ai commented 2 years ago

The problem is that you are using JS file for browsers in Node.js.

You should not run JS bundle after webpack in Node.js.

kapitanluffy commented 2 years ago

Do you mind elaborating? What I do is transpile ts files with webpack using babel and run the transpiled file in dist directory. Is there something wrong with the webpack config?

ai commented 2 years ago

Webpack is generating files for browsers. They will not be compatible with Node.js because some JS API are different in browser and Node.js.

There are two options:

  1. Run your app in Node.js without webpack (ideal for testing webapp)
  2. Use universal APIs only. For instance you can use non-secure ID generation of you don't need a secure method.