vite#UserConfig TypeScript Examples

The following examples show how to use vite#UserConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
config: UserConfig = {
  plugins: [
    vue({
      include: [/\.vue$/, /\.md$/],
    }),
    md(),
    ssr(),
  ],
  clearScreen: false,
  // Neeed if using an ESM-only library. This is not the case of this example and it's, in general, a rare case. But such situation will increasingly occur as ESM-only libraries emerge.
  build: {
    rollupOptions: {
      output: {
        format: 'es', // Transpile to ESM instead of CJS
      },
    },
  },
}
Example #2
Source File: vite.config.ts    From vite-plugin-qiankun with MIT License 6 votes vote down vote up
baseConfig:UserConfig = {
  plugins: [
    ...(
      useDevMode ? [] : [
        reactRefresh()
      ]
    ),
    qiankun('viteapp', {
      useDevMode
    })
  ],
  server: {
    fsServe: {
      root: path.join(process.cwd(), '../../')
    },
    port: 7106,
    cors: true,
  },
}
Example #3
Source File: vite.config.ts    From netless-app with MIT License 6 votes vote down vote up
configFn = defineConfig(options => {
  const config = createViteConfig({ entry: resolve("./src/index.tsx") })(options) as UserConfig;
  config.plugins = [];
  Object.assign(config, {
    esbuild: {
      jsxFactory: "h",
      jsxFragment: "Fragment",
      jsxInject: `import { h, Fragment } from 'preact'`,
    },
  });
  return config;
})
Example #4
Source File: index.ts    From vite-plugin-vue-i18n with MIT License 6 votes vote down vote up
function normalizeConfigResolveAliias(config: UserConfig): void {
  // NOTE: cannot resolve Optional Chaining in jest E2E ...
  if (config.resolve && config.resolve.alias) {
    return
  }

  if (!config.resolve) {
    config.resolve = { alias: [] }
  } else if (!config.resolve.alias) {
    config.resolve.alias = []
  }
}
Example #5
Source File: plugin.ts    From vite-ssr with MIT License 6 votes vote down vote up
// FIXME
// Vite 2.6.0 introduced a bug where `import.meta` is not populated
// correctly in optimized dependencies. At the same time, all the
// subdependencies in Style Collectors must be optimized.
function fixReactDeps(
  config: Pick<UserConfig, 'optimizeDeps' | 'root'>,
  libPath: string
) {
  const styleCollectorDeps = {
    'styled-components': ['styled-components'],
    'material-ui-core-v4': ['@material-ui/core/styles'],
    emotion: ['@emotion/cache', '@emotion/react'],
  } as const

  const styleCollectors = Object.keys(styleCollectorDeps).filter((sc) => {
    try {
      require.resolve(sc)
      return true
    } catch (error) {
      return false
    }
  })

  if (config.optimizeDeps) {
    config.optimizeDeps.include?.push(
      ...styleCollectors.flatMap(
        (sc) => styleCollectorDeps[sc as keyof typeof styleCollectorDeps]
      )
    )

    config.optimizeDeps.exclude = config.optimizeDeps.exclude || []
    config.optimizeDeps.exclude.push(
      ...styleCollectors.map(
        (sc) => pluginName + libPath + '/style-collectors/' + sc
      )
    )
  }
}
Example #6
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
createViteConfig = async (context: BuildContext, input: ViteOptions): Promise<UserConfig> => {
    if (context.entries.length !== 1) {
        logger.error('Currently vite driver only supports one application entry.');
        process.exit(24);
    }

    // 兼容一下`publicPath`有没有最后的`/`的情况
    const options = {...input, publicPath: input.publicPath + (input.publicPath.endsWith('/') ? '' : '/')};
    const parts = await Promise.all(factories.map(v => v(context, options)));
    const config = parts.reduce((output, current) => mergeConfig(output, current)) as FinalizableViteConfiguration;
    const serverFinalized = {
        ...config,
        server: await context.projectSettings.devServer.finalize(config.server, context),
    };
    warnAndExitOnInvalidFinalizeReturn(serverFinalized, 'devServer');

    const finalized = await context.projectSettings.build.finalize(serverFinalized, context);
    warnAndExitOnInvalidFinalizeReturn(finalized, 'build');

    return finalized;
}
Example #7
Source File: build.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
function getRoot(config: UserConfig): string {
  let root = config.root || process.cwd()
  assertUsage(
    pathIsAbsolute(root),
    // Looking at Vite's source code, Vite does seem to normalize `root`.
    // But this doens't seem to be always the case, see https://github.com/brillout/vite-plugin-ssr/issues/208
    'The `root` config in your `vite.config.js` should be an absolute path. (I.e. `/path/to/root` instead of `../path/to/root`.)',
  )
  root = posixPath(root)
  return root
}
Example #8
Source File: build.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
function browserEntryPoints(config: UserConfig): Record<string, string> {
  const root = getRoot(config)
  assert(pathIsAbsolute(root))

  const browserEntries = glob.sync(`${root}/**/*.page.client.*([a-zA-Z0-9])`, {
    ignore: ['**/node_modules/**'],
  })

  const entryPoints: Record<string, string> = {}
  for (const filePath of browserEntries) {
    assert(pathIsAbsolute(filePath))
    const outFilePath = pathRelativeToRoot(filePath, config)
    entryPoints[outFilePath] = filePath
  }
  return entryPoints
}
Example #9
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
config: UserConfig = {
  plugins: [react(), mdx(), ssr()],
  clearScreen: false,
  resolve: {
    alias: {
      // Needed for MDX, see https://github.com/mdx-js/mdx/discussions/1794#discussioncomment-1581513
      'react/jsx-runtime': 'react/jsx-runtime.js',
    },
  },
  optimizeDeps: { include: ['react/jsx-runtime.js'] },
}
Example #10
Source File: vite.config.ts    From vite-react-jsx with MIT License 6 votes vote down vote up
config: UserConfig = {
  plugins: [reactRefresh(), reactJsx()],
  build: {
    // The minified bundle works as expected.
    minify: false,
    // Source maps are generated properly.
    sourcemap: true,
  },
}
Example #11
Source File: vite.config.ts    From elenext with MIT License 6 votes vote down vote up
config: UserConfig = {
  server: {
    port: 8080,
  },
  assetsInclude: ['src/assets'],
  optimizeDeps: {
    exclude: ['elenext'],
  },
  plugins: [
    vitePluginSyncmd(),
    createPlugin({
      markdownIt: {
        plugins: [...containers],
      },
      highlight: {
        theme: 'one-dark',
      },
    }),
    vue({
      include: [...vueDocFiles],
    }),
  ],
}
Example #12
Source File: vite.config.ts    From vite-plugin-md-preview with MIT License 6 votes vote down vote up
config: UserConfig = {
  build: {
    outDir: 'playground/dist',
    emptyOutDir: true,
  },
  plugins: [
    vue({
      include: [/\.vue$/, /\.md$/],
    }),
    vueJsx(),
    Markdown({
      transforms: {
        before: transformer,
      },
      markdownItUses: [[shiki, { theme: 'vitesse-light' }]],
    }),
    MarkdownVuePreview({
      shiki: {
        theme: 'vitesse-light',
      },
    }),
  ],
}
Example #13
Source File: vite.config.ts    From vite-plugin-legacy with MIT License 6 votes vote down vote up
config: UserConfig = {
  build: {
    sourcemap: true,
  },
  esbuild: {
    target: 'es2018',
  },
  plugins: [
    reactPlugin,
    legacyPlugin({
      targets: 'defaults',
    }),
  ],
}
Example #14
Source File: vite.config.ts    From foundryvtt-lancer with GNU General Public License v3.0 5 votes vote down vote up
config: UserConfig = {
  root: "src/",
  base: "/systems/lancer/",
  publicDir: path.resolve(__dirname, "public"),
  server: {
    port: 30001,
    open: true,
    proxy: {
      "^(?!/systems/lancer)": "http://localhost:30000/",
      "/socket.io": {
        target: "ws://localhost:30000",
        ws: true,
      },
    },
  },
  resolve: {
    alias: [
      {
        find: "./runtimeConfig",
        replacement: "./runtimeConfig.browser",
      },
    ],
  },
  optimizeDeps: {
    exclude: ["machine-mind"], // machine-mind triggers https://github.com/evanw/esbuild/issues/1433
    include: ["lancer-data", "jszip", "axios", "readonly-proxy"], // machine-mind's cjs dependencies
  },
  build: {
    outDir: path.resolve(__dirname, "dist"),
    emptyOutDir: true,
    sourcemap: true,
    brotliSize: true,
    terserOptions: {
      mangle: false,
      keep_classnames: true,
      keep_fnames: true,
    },
    lib: {
      name: "lancer",
      entry: path.resolve(__dirname, "src/lancer.ts"),
      formats: ["es"],
      fileName: "lancer",
    },
  },
  plugins: [
    svelte({
      configFile: "../svelte.config.cjs", // relative to src/
    }),
    checker({
      typescript: true,
      // svelte: { root: __dirname },
    }),
    visualizer({
      gzipSize: true,
      template: "treemap",
    }),
  ],
}
Example #15
Source File: build.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
function entryPoints(config: UserConfig): Record<string, string> {
  if (isSSR_config(config)) {
    return serverEntryPoints()
  } else {
    return browserEntryPoints(config)
  }
}
Example #16
Source File: main.ts    From frontend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
config: StorybookConfig & { viteFinal: (viteConfig: UserConfig) => Promise<UserConfig> } = {
  stories: [
    '../components/**/*.stories.mdx',
    '../components/**/*.stories.@(js|jsx|ts|tsx)',
    '../../icons/index.stories.tsx'
  ],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials'
  ],
  framework: '@storybook/react',
  viteFinal: async (viteConfig) => {
    // workaround for vite build
    // Refs: https://github.com/eirslett/storybook-builder-vite/issues/55#issuecomment-871800293
    viteConfig.root = dirname(require.resolve('storybook-builder-vite'))
    /*
    * About auto-generated component docs:
    * Please use FC<Props> instead of React.FC<Props> to declare component.
    * https://github.com/styleguidist/react-docgen-typescript/issues/323
    * https://github.com/styleguidist/react-docgen-typescript/issues/393
    * */
    !viteConfig.plugins && (viteConfig.plugins = [])
    viteConfig.plugins.push(reactDocgenTypescript())
    /* WIP: Temporary patch for style */
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    viteConfig.plugins.push({
      transform (source, id) {
        if (id.endsWith('.stories.tsx') && id.includes('components')) {
          return `${source}
          import './style'`
        }
        return source
      }
    } as PluginOption)

    viteConfig.plugins.push(svgr())
    return viteConfig
  },
  core: {
    builder: 'storybook-builder-vite'
  }
}
Example #17
Source File: build.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
function pathRelativeToRoot(filePath: string, config: UserConfig): string {
  assert(pathIsAbsolute(filePath))
  const root = getRoot(config)
  assert(pathIsAbsolute(root))
  return pathRelative(root, filePath)
}
Example #18
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
config: UserConfig = {
  plugins: [vue(), ssr()],
}
Example #19
Source File: build.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
function getOutDir(config: UserConfig): string {
  let outDir = config.build?.outDir
  if (!outDir) {
    outDir = 'dist'
  }
  return config.build?.ssr ? `${outDir}/server` : `${outDir}/client`
}
Example #20
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
run = async (buildContext: BuildContext, cmd: PlayCommandLineArgs, target: string) => {
    const entryModified: BuildContext = {
        ...buildContext,
        entries: buildContext.entries.map(v => ({...v, file: '/playground-entry.jsx'})),
    };
    const options: ViteOptions = {
        clean: false,
        sourceMaps: true,
        proxyDomain: buildContext.projectSettings.devServer.defaultProxyDomain,
        defaultEntry: 'index',
        publicPath: '/',
    };
    const config = await createViteConfig(entryModified, options);
    const pluginOptions = {
        cwd: cmd.cwd,
        componentTypeName: resolveComponentName(target),
        componentModulePath: path.resolve(buildContext.cwd, target),
        globalSetupModulePath: cmd.setup
            ? path.resolve(cmd.cwd, cmd.setup)
            : buildContext.projectSettings.play.defaultGlobalSetup,
        enableConcurrentMode: cmd.concurrentMode ?? buildContext.projectSettings.play.defaultEnableConcurrentMode,
    };
    const socketProxyEnabeld: UserConfig = {
        ...config,
        server: {
            ...config.server,
            proxy: {
                ...config.server?.proxy,
                '/io-play': {
                    target: 'http://localhost:9998/io-play',
                    ws: true,
                },
            },
        },
        plugins: [
            playEntryPlugin(pluginOptions),
            ...config.plugins ?? [],
        ],
    };
    const server = await createServer(socketProxyEnabeld);
    await server.listen();
    const protocol = buildContext.projectSettings.devServer.https?.client ? 'https' : 'http';
    const url = `${protocol}://${cmd.host}:${cmd.port}/${buildContext.projectSettings.devServer.openPage}`;
    logger.infoHighlight(`Your application is running here: ${url}`);
}
Example #21
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
config: UserConfig = {
  plugins: [solidPlugin({ ssr: true }), ssr()],
  build: {
    polyfillDynamicImport: false,
  },
}
Example #22
Source File: vite.config.ts    From vite-plugin-compress with MIT License 5 votes vote down vote up
config: UserConfig = {
  plugins: [
    compress({
      verbose: true,
    }),
  ],
}
Example #23
Source File: main.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
config: CustomizedStorybookConfig = {
  'stories': ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  'addons': ['@storybook/addon-links', '@storybook/addon-essentials'],
  'core': {
    'builder': 'storybook-builder-vite',
  },
  viteFinal(storybookConfig, { configType }) {
    if (configType === 'DEVELOPMENT') {
      storybookConfig.build = {}
    }
    storybookConfig.build.target = ''
    const viteConfig = _viteConfig as UserConfig
    const vitePlugins = Array.isArray(viteConfig.plugins) ? viteConfig.plugins.flat() : []
    const filteredVitePlugins = vitePlugins.filter(
      (plugin) =>
        // @ts-ignore totally justified ignore
        plugin.name !== 'vite:react-babel' &&
        // @ts-ignore totally justified ignore
        plugin.name !== 'vite:react-refresh' &&
        // @ts-ignore totally justified ignore
        plugin.name !== 'vite:react-jsx' &&
        // @ts-ignore totally justified ignore
        plugin.name !== 'vite-plugin-checker'
    )
    const merged: UserConfig = {
      ...storybookConfig,
      plugins: [...(storybookConfig.plugins || []), ...filteredVitePlugins],
      optimizeDeps: {
        ...storybookConfig.optimizeDeps,
        include: [...(storybookConfig.optimizeDeps?.include || []), ...(viteConfig.optimizeDeps?.include || [])],
      },
      resolve: {
        alias: {
          ...storybookConfig.resolve?.alias,
          ...viteConfig.resolve?.alias,
        },
      },
    }
    return merged
  },
}
Example #24
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
config: UserConfig = {
  plugins: [react(), ssr()],
}
Example #25
Source File: vite.config.ts    From vite-plugin-ssr with MIT License 5 votes vote down vote up
config: UserConfig = {
  resolve: {
    alias: {
      '#root': __dirname,
    },
  },
  plugins: [react(), ssr()],
}
Example #26
Source File: index.ts    From vite-plugin-vue-i18n with MIT License 4 votes vote down vote up
function pluginI18n(
  options: VitePluginVueI18nOptions = { forceStringify: false }
): Plugin {
  debug('plugin options:', options)

  // use `normalizePath` for `options.include`
  let include = options.include
  if (include) {
    if (isArray(include)) {
      include = include.map(item => normalizePath(item))
    } else if (isString(include)) {
      include = normalizePath(include)
    }
  }

  const filter = createFilter(include)
  const runtimeOnly = isBoolean(options.runtimeOnly)
    ? options.runtimeOnly
    : true
  const compositionOnly = isBoolean(options.compositionOnly)
    ? options.compositionOnly
    : true
  const fullIinstall = isBoolean(options.fullInstall)
    ? options.fullInstall
    : true
  const defaultSFCLang = isString(options.defaultSFCLang)
    ? options.defaultSFCLang
    : undefined
  const globalSFCScope = isBoolean(options.globalSFCScope)
    ? options.globalSFCScope
    : false
  let config: ResolvedConfig | null = null

  return {
    name: 'vite-plugin-vue-i18n',

    config(config: UserConfig, { command }) {
      if (command === 'build' && runtimeOnly) {
        normalizeConfigResolveAliias(config)
        if (isArray(config.resolve!.alias)) {
          config.resolve!.alias.push({
            find: 'vue-i18n',
            replacement: 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
          })
        } else {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          ;(config.resolve!.alias as any)['vue-i18n'] =
            'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
        }
        debug('set vue-i18n runtime only')
      }

      config.define = config.define || {}
      config.define['__VUE_I18N_LEGACY_API__'] = !compositionOnly
      debug(
        `set __VUE_I18N_LEGACY_API__ is '${config.define['__VUE_I18N_LEGACY_API__']}'`
      )

      config.define['__VUE_I18N_FULL_INSTALL__'] = fullIinstall
      debug(
        `set __VUE_I18N_FULL_INSTALL__ is '${config.define['__VUE_I18N_FULL_INSTALL__']}'`
      )

      config.define['__VUE_I18N_PROD_DEVTOOLS__'] = false
    },

    configResolved(_config: ResolvedConfig) {
      // store config
      config = _config

      // json transform handling
      const jsonPlugin = config.plugins.find(p => p.name === 'vite:json')
      if (jsonPlugin) {
        const orgTransform = jsonPlugin.transform // backup @rollup/plugin-json
        jsonPlugin.transform = async function (code: string, id: string) {
          if (!/\.json$/.test(id)) {
            return null
          }
          if (filter(id)) {
            const map = this.getCombinedSourcemap()
            debug('override json plugin', code, map)
            return Promise.resolve({
              code,
              map
            })
          } else {
            debug('org json plugin')
            return orgTransform!.apply(this, [code, id])
          }
        }
      }
    },

    resolveId(id: string) {
      if (id === INTLIFY_BUNDLE_IMPORT_ID) {
        return id
      }
    },

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    async load(id: string, ssr: boolean) {
      if (id === INTLIFY_BUNDLE_IMPORT_ID && include) {
        let resourcePaths = [] as string[]
        const includePaths = isArray(include) ? include : [include]
        for (const inc of includePaths) {
          resourcePaths = [...(await fg(inc))]
        }
        // TODO: source-map
        const code = await generateBundleResources(
          resourcePaths,
          config != null ? config.isProduction : false,
          options.forceStringify!
        )
        return Promise.resolve(code)
      }
    },

    async handleHotUpdate({ file, server }) {
      if (/\.(json5?|ya?ml)$/.test(file)) {
        const module = server.moduleGraph.getModuleById(
          INTLIFY_BUNDLE_IMPORT_ID
        )
        if (module) {
          server.moduleGraph.invalidateModule(module)
          return [module!]
        }
      }
    },

    async transform(code: string, id: string) {
      const { filename, query } = parseVueRequest(id)
      debug('transform', id, JSON.stringify(query))

      const parseOptions = getOptions(
        filename,
        config != null ? config.isProduction : false,
        query as Record<string, unknown>,
        options.forceStringify
      ) as CodeGenOptions
      debug('parseOptions', parseOptions)

      let langInfo = 'json'
      if (!query.vue) {
        if (/\.(json5?|ya?ml)$/.test(id) && filter(id)) {
          langInfo = path.parse(filename).ext
          // NOTE:
          // `.json` is handled default in vite, and it's transformed to JS object.
          let _source = code
          if (langInfo === '.json') {
            _source = await getRaw(id)
          }
          const generate = /\.?json5?/.test(langInfo)
            ? generateJSON
            : generateYAML
          const { code: generatedCode } = generate(_source, parseOptions)
          debug('generated code', generatedCode)
          // TODO: error handling & sourcempa
          return Promise.resolve(generatedCode)
        } else {
          return Promise.resolve(code)
        }
      } else {
        // for Vue SFC
        if (isCustomBlock(query as Record<string, unknown>)) {
          if ('src' in query) {
            if (isString(query.lang)) {
              langInfo = query.lang === 'i18n' ? 'json' : query.lang
            } else if (defaultSFCLang) {
              langInfo = defaultSFCLang
            }
          } else {
            if (isString(query.lang)) {
              langInfo = query.lang
            } else if (defaultSFCLang) {
              langInfo = defaultSFCLang
            }
          }
          if (!parseOptions.isGlobal && globalSFCScope) {
            parseOptions.isGlobal = true
          }
          const generate = /\.?json5?/.test(langInfo)
            ? generateJSON
            : generateYAML
          const { code: generatedCode } = generate(code, parseOptions)
          debug('generated code', generatedCode)
          // TODO: error handling & sourcempa
          return Promise.resolve(generatedCode)
        } else {
          return Promise.resolve(code)
        }
      }
    }
  }
}