For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt, and this page is available as Markdown at /next/zh/api/rspeedy/rspeedy.source.define.md.
Rspeedy logo
Rspeedy
  • 简体中文
  • Home > @lynx-js/rspeedy > Source > define

    Source.define property

    The define options is used to define some values or expressions at compile time.

    Signature:

    define?: Rspack.DefinePluginOptions;

    Default Value

    undefined

    Remarks

    • If the value provided is a string, it will be utilized as a code fragment.

    • If the value provided is an object, all its keys will be defined in the same manner.

    • If the value isn't a string, it will be stringified, with functions included.

    • Notably, if a typeof prefix is attached to the key, it will be exclusively defined for typeof calls."

    Example 1

    Using define for environment variables.

    import { defineConfig } from '@lynx-js/rspeedy'
    export default defineConfig({
      source: {
        define: {
          BUILD_VERSION: JSON.stringify(process.env.BUILD_VERSION ?? 'unknown_version'),
          'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        },
      },
    })

    Expressions will be replaced with the corresponding code fragments:

    const version = BUILD_VERSION;
    if (process.env.NODE_ENV === 'development') {}
    
    // ⬇️ Turn into being...
    const version = "unknown_version";
    if ("development" === 'development') {}

    Example 2

    Using define for typeof.

    import { defineConfig } from '@lynx-js/rspeedy'
    export default defineConfig({
      source: {
        define: {
          'typeof window': JSON.stringify("undefined"),
        },
      },
    })

    The typeof expressions will be replaced with the corresponding code fragments:

    if (typeof window !== 'undefined') {}
    
    // ⬇️ Turn into being...
    if ("undefined" !== 'undefined') {}

    Example 3

    Using define with objects.

    import { defineConfig } from '@lynx-js/rspeedy'
    export default defineConfig({
      source: {
        define: {
          'import.meta': {
            foo: JSON.stringify('foo'),
            bar: { baz: 0 },
          },
        },
      },
    })

    Expressions will be replaced with the corresponding code fragments:

    console.log(import.meta)
    
    // ⬇️ Turn into being...
    console.log({ foo: "foo", bar: { baz: 0 } })
    除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。