vite#Plugin TypeScript Examples

The following examples show how to use vite#Plugin. 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: index.ts    From reskript with MIT License 6 votes vote down vote up
export default function svgComponentPlugin({displayName = false}: Options = {}): Plugin {
    const root = {value: process.cwd()};

    return {
        name: 'reskript:svg-to-component',
        enforce: 'pre',
        configResolved(config) {
            root.value = config.root;
        },
        async resolveId(source, importer, options) {
            if (source.endsWith('.svg?react')) {
                const resourceId = source.replace(/\?react$/, '');
                const resolved = await this.resolve(resourceId, importer, {...options, skipSelf: true});
                return resolved && VIRTURL_ID_PREFIX + resolved.id;
            }
        },
        async load(id) {
            if (id.startsWith(VIRTURL_ID_PREFIX)) {
                // Vite会把`//`给处理成`/`,所以这里在去掉前缀的时候,又要保留路径上的`/`
                const resource = id.slice(VIRTURL_ID_PREFIX.length - 1);
                this.addWatchFile(resource);
                const svgSource = await fs.readFile(resource, 'utf-8');
                const code = await transformSvgToComponent(svgSource, {resource, displayName});
                return code;
            }
        },
    };
}
Example #2
Source File: transform.ts    From telefunc with MIT License 6 votes vote down vote up
function transform(): Plugin {
  let root: string
  return {
    name: 'telefunc:transform',
    enforce: 'pre',
    configResolved: (config) => {
      root = toPosixPath(config.root)
      assert(root)
    },
    async transform(code, id, options) {
      if (!id.includes('.telefunc.')) {
        return
      }
      if (!isSSR_options(options)) {
        return transformTelefuncFile(code, id, root)
      } else {
        if (id.endsWith('.ts')) {
          return generateShield(code)
        }
      }
    }
  }
}
Example #3
Source File: index.ts    From convue with MIT License 6 votes vote down vote up
export default function HtmlPlugin(userOptions: Options = {}): Plugin {
  let config: ResolvedConfig | undefined;
  let options: Options = userOptions;
  let title: string;

  return {
    name: 'vite-plugin-html',
    enforce: 'pre',
    configResolved(_config) {
      config = _config;
      options.root = config.root;
      if (options.head && options.head.title) {
        title = options.head.title;
      } else {
        const packageJson = JSON.parse(
          fs.readFileSync(normalizePath(resolve(config.root, 'package.json')), 'utf-8')
        );
        title = packageJson.name;
        debug('title', title);
      }
    },
    transformIndexHtml(html) {
      return html
        .replace(/<!-- TITLE -->/, title)
        .replace(/<!-- HEAD -->/, genarateHeadElements(options))
        .replace(/<!-- APP -->/, genrateLoading(options));
    },
  };
}
Example #4
Source File: index.ts    From vite-react-cil with MIT License 6 votes vote down vote up
export default function createVitePlugins() {
  const vitePlugins: (Plugin | Plugin[])[] = [
    /**
     * @description 必须默认项
     */
    reactRefresh(),
    configSvgIcons(),
    // configStyleImport(),
  ];
  VITE_APP_ESLINT && vitePlugins.push(...configEslint());
  VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig());
  VITE_APP_LEGACY &&
    vitePlugins.push(
      legacy({
        targets: ['ie >= 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      }),
    );
  return vitePlugins;
}
Example #5
Source File: index.ts    From ant-simple-draw with MIT License 6 votes vote down vote up
export default function createVitePlugins() {
  const vitePlugins: (Plugin | Plugin[])[] = [
    /**
     * @description 必须默认项
     */
    reactRefresh(),
    configSvgIcons(),
    configStyleImport(),
  ];
  VITE_APP_ESLINT && vitePlugins.push(...configEslint());
  VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig());
  VITE_APP_LEGACY &&
    vitePlugins.push(
      legacy({
        targets: ['ie >= 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      }),
    );
  return vitePlugins;
}
Example #6
Source File: vite.config.ts    From vue-i18n-next with MIT License 6 votes vote down vote up
backend = (): Plugin => ({
  name: 'backend',
  configureServer(server) {
    server.middlewares.use(bodyParser.json())
    // `/api/resources/en` endpoint returns the response as `en` resources
    server.middlewares.use('/api/resources/en', (req, res) => {
      serialize(res, en)
      res.end()
    })
    // `/api/resources/ja` endpoint returns the response as `ja` resources
    server.middlewares.use('/api/resources/ja', (req, res) => {
      serialize(res, ja)
      res.end()
    })
  }
})
Example #7
Source File: injection.ts    From vite-plugin-vue-i18n with MIT License 6 votes vote down vote up
export default function IntlifyVue(values: InjectionValues = {}): Plugin {
  let config: ResolvedConfig | null = null

  return {
    enforce: 'post',
    name: 'vite-plugin-vue-i18n:intlify-vue',
    configResolved(_config: ResolvedConfig) {
      config = _config
    },
    transform(code: string, id: string) {
      debug('transform', id)
      if (id.endsWith('.vue')) {
        const magic = new MagicString(code)
        const indentifier = '_sfc_main'
        const index = code.indexOf(`export default ${indentifier}`)
        magic.appendLeft(index, generateCode(values, indentifier, id, config!))
        return {
          code: magic.toString(),
          map: magic.generateMap()
        }
      }
    }
  }
}
Example #8
Source File: find-unused-file-plugin.ts    From hexon with GNU General Public License v3.0 6 votes vote down vote up
export default function unused(): Plugin {
  return {
    name: "find-unused-file",

    load(id) {
      if (allFile.has(id)) {
        allFile.delete(id)
      }
      return null
    },

    buildEnd() {
      log()
    },
  }
}
Example #9
Source File: server.ts    From reskript with MIT License 6 votes vote down vote up
export default function viertualEntryServerPlugin(options: ServerOptions): Plugin {
    const historyOptions = {
        index: `/${options.name}.html`,
        disableDotRule: true,
        htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
    };

    return {
        name: 'reskript:virtual-entry-server',
        enforce: 'pre',
        configureServer(server) {
            const before = createMiddlewareHook();
            const after = createMiddlewareHook();
            options.customizeMiddleware({before, after});
            before.items().forEach(v => server.middlewares.use(v.path, v.middleware));
            // @ts-expect-error
            server.middlewares.use(history(historyOptions));
            server.middlewares.use(
                `/${options.name}.html`,
                async (req, res) => {
                    res.statusCode = 200;
                    res.setHeader('Content-Type', 'text/html');
                    res.end(options.content);
                }
            );
            after.items().forEach(v => server.middlewares.use(v.path, v.middleware));
        },
    };
}
Example #10
Source File: dev.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
function dev(): Plugin {
  return {
    name: 'vite-plugin-ssr:dev',
    apply: 'serve',
    config: () => ({
      ssr: { external: ['vite-plugin-ssr'] },
      optimizeDeps: {
        entries: ['**/*.page.*([a-zA-Z0-9])', '**/*.page.client.*([a-zA-Z0-9])'],
        exclude: [
          // We exclude the client code to support `import.meta.glob()`
          'vite-plugin-ssr/client',
          'vite-plugin-ssr/client/router',
          // We cannot add these to `optimizeDeps.include` because of `pnpm`
          '@brillout/libassert',
          '@brillout/json-s',
          '@brillout/json-s/parse',
          '@brillout/json-s/stringify',
        ],
      },
    }),
  }
}
Example #11
Source File: index.ts    From vite-vue3-ts with MIT License 6 votes vote down vote up
export function createVitePlugins(isBuild: boolean) {
  const vitePlugins: (Plugin | Plugin[])[] = [
    // vue支持
    vue(),
    // JSX支持
    vueJsx(),
    // 自动按需引入组件
    autoRegistryComponents(),
    // 自动按需引入依赖
    AutoImportDeps(),
  ];

  // @vitejs/plugin-legacy
  // isBuild && vitePlugins.push(legacy());

  // rollup-plugin-gzip
  isBuild && vitePlugins.push(configCompressPlugin());

  // vite-plugin-svg-icons
  vitePlugins.push(configSvgIconsPlugin(isBuild));

  // vite-plugin-mock
  vitePlugins.push(configMockPlugin(isBuild));

  // rollup-plugin-visualizer
  vitePlugins.push(configVisualizerConfig());

  // vite-plugin-style-import
  vitePlugins.push(configStyleImportPlugin(isBuild));

  return vitePlugins;
}
Example #12
Source File: onlineDemoBuildPlugin.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
onlineDemoBuildPlugin = (): Plugin => ({
  name: 'online-demo-build-plugin',
  enforce: 'pre',
  apply: 'build',

  transform(code, id) {
    if (!/\.(t|j)sx$/.test(id) || id.includes('node_modules')) {
      return code
    }

    const result = transformSync(code, {
      filename: id,
      babelrc: false,
      configFile: false,
      compact: false,
      parserOpts: {
        sourceType: 'module',
        plugins: [
          'typescript',
          'jsx',
        ],
      },
      plugins: [
        'react-dev-inspector/plugins/babel',
      ],
    })

    return result?.code
  },
})
Example #13
Source File: index.ts    From vite-plugin-sass-dts with MIT License 6 votes vote down vote up
export default function Plugin(option: PluginOption = {}): Plugin {
  let cacheConfig: FinalConfig
  const enabledMode = option.enabledMode || ['development']
  return {
    name: 'vite-plugin-sass-dts',
    async configResolved(config) {
      const prettierOptions = (await prettier.resolveConfig(config.root)) || {}
      cacheConfig = {
        ...config,
        prettierOptions: { ...prettierOptions, filepath: '*.d.ts' },
      }
    },
    handleHotUpdate(context) {
      if (!isCSSModuleRequest(context.file)) return
      main(context.file, cacheConfig, option)
      return
    },
    transform(code, id) {
      if (!enabledMode.includes(cacheConfig.env.MODE)) {
        return { code }
      }

      const fileName = id.replace('?used', '')
      if (!isCSSModuleRequest(fileName)) return { code }

      main(fileName, cacheConfig, option)

      return { code }
    },
  }
}
Example #14
Source File: md-transform.ts    From vue-components-lib-seed with MIT License 6 votes vote down vote up
export function MarkdownTransform(): Plugin {
  return {
    name: 'element-plus-md-transform',
    enforce: 'pre',
    async transform(code, id) {
      if (!id.endsWith('.md')) return

      const componentId = path.basename(id, '.md')

      if (!components.includes(componentId)) return

      const append = {
        headers: [],
        footers: [],
        scriptSetups: [
          `const demos = import.meta.globEager('../../../src/packages/${componentId}/demo/demo*.vue')`,
        ],
      }

      code += `
<script setup>
${append.scriptSetups}
</script>   
`

      return {
        code,
      }
    },
  }
}
Example #15
Source File: plugin.ts    From vite-react-jsx with MIT License 6 votes vote down vote up
export default function viteReactJsx(): Plugin {
  return {
    name: 'vite:react-jsx',
    enforce: 'pre',
    config: () => ({
      resolve: {
        dedupe: ['react', 'react-dom'],
      },
    }),
    configResolved(config) {
      if (config.command === 'build') {
        Object.assign(this, getRuntimeLoader(config))
        this.transform = getTransformer({
          sourceMaps: !!config.build.sourcemap,
        })
      } else {
        const jsxRE = /\.[tj]sx$/
        const reactRE = /(^|\n)import React[ ,]/

        // Just use React.createElement in serve mode
        this.transform = function (code, id) {
          if (jsxRE.test(id) && !reactRE.test(code)) {
            return `import React from 'react'; ` + code
          }
        }
      }
    },
  }
}
Example #16
Source File: build.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
function build(): Plugin {
  let isSsrBuild: boolean | undefined
  return {
    name: 'vite-plugin-ssr:build',
    apply: 'build',
    config: (config) => {
      isSsrBuild = isSSR_config(config)
      const input = {
        ...entryPoints(config),
        ...normalizeRollupInput(config.build?.rollupOptions?.input),
      }
      return {
        build: {
          outDir: getOutDir(config),
          manifest: true,
          rollupOptions: { input },
          polyfillDynamicImport: false,
        },
        //*
        ssr: { external: ['vite-plugin-ssr'] },
        /*/
        // Try Hydrogen's `noExternal: true` bundling strategy for Cloudflare Workers
        ssr: { noExternal: true },
        //*/
      }
    },
    transform: (_src, id) => {
      assert(isSsrBuild === true || isSsrBuild === false)
      return removeClientCode(isSsrBuild, id) || undefined
    },
  }
}
Example #17
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
export default function cssBindPlugin({classNamesModule = 'classnames/bind'}: Options = {}): Plugin {
    return {
        name: 'reskript:css-bind',
        enforce: 'post',
        resolveId(id) {
            if (id === ASSIGN_MODULE_ID || id === BIND_MODULE_ID) {
                return id;
            }
        },
        transform(code, id) {
            if (isStyle(id)) {
                return transformCssModulesExport(code);
            }
        },
        async load(id) {
            if (id === ASSIGN_MODULE_ID) {
                return ASSIGN_MODULE;
            }

            // 在`classnames`完成ES化以前,不得不在这里转换一下
            if (id === BIND_MODULE_ID) {
                const resolved = await this.resolve(classNamesModule);
                if (resolved) {
                    const code = await fs.readFile(resolved.id, 'utf-8');
                    const transformed = await transformWithEsbuild(code, resolved.id, {format: 'esm'});
                    return transformed.code;
                }
            }
        },
    };
}
Example #18
Source File: index.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
// Return as `any` to avoid Plugin type mismatches when there are multiple Vite versions installed
function plugin(): any {
  const plugins: Plugin[] = [
    dev(),
    build(),
    manifest(),
    importBuild(getImportBuildCode()),
    packageJsonFile(),
    transformPageServerFiles(),
    removeRequireHookPlugin(),
  ]
  return plugins as any
}
Example #19
Source File: plugin.ts    From reskript with MIT License 6 votes vote down vote up
export default function playEntryPlugin(options: Options): Plugin {
    return {
        name: 'reskript:play-entry',
        enforce: 'pre',
        async config() {
            return {
                optimizeDeps: {
                    entries: [
                        options.componentModulePath,
                    ],
                },
            };
        },
        resolveId(id) {
            if (id === '/playground-entry.jsx') {
                return id;
            }
        },
        async load(id) {
            if (id === '/playground-entry.jsx') {
                const content = await fs.readFile(resolveEntryPath(options.enableConcurrentMode), 'utf-8');
                return buildEntryScript(content, options);
            }
        },
    };
}
Example #20
Source File: index.ts    From convue with MIT License 5 votes vote down vote up
function routePlugin(userOptions: UserOptions = {}): Plugin {
  let config: ResolvedConfig | undefined;
  let filesPath: string[] = [];
  let generatedLocales: any[] | null | undefined;

  const options: ResolvedOptions = resolveOptions(userOptions);

  if (options.useCookie === true) {
    options.useCookie = {
      cookieKey: 'i18n',
      expires: 365,
    }
  }

  return {
    name: 'vite-plugin-store',
    enforce: 'pre',
    configResolved(_config) {
      config = _config;
      options.root = config.root;
      options.localesDirPath = normalizePath(resolve(config.root, options.dir));
      debug('localesDirPath', options.localesDirPath);
    },
    resolveId(id) {
      if (id === ID) return ID;
    },
    async load(id) {
      if (id === ID) {
        debug('Loading files...');

        filesPath = await getLocalesPath(options);

        debug('FilesPath: %O', filesPath);

        if (!generatedLocales) generatedLocales = generateLocales(filesPath, options);

        debug('Components: %O', generatedLocales);

        const clientCode = generateClientCode(generatedLocales, options);

        debug('Client code: %O', clientCode)

        return clientCode;
      }
    },
    async handleHotUpdate({ file, server }) {
      const extensionsRE = new RegExp(`\\.(${options.extensions.join('|')})$`);
      const storeDir = options.dir;
      const localesDirPath = options.localesDirPath;
      // Handle pages HMR
      if (
        (file.startsWith(localesDirPath) || file.startsWith(localesDirPath)) &&
        extensionsRE.test(file)
      ) {
        let needReload = false;

        // HMR on new file created
        // Otherwise, handle HMR from custom block
        if (file.includes(storeDir)) {
          if (
            !filesPath.includes(file.replace(`${localesDirPath}/`, ''))
          ) {
            generatedLocales = null;
            needReload = true;
          }
        }

        if (needReload) {
          const { moduleGraph } = server;
          const module = moduleGraph.getModuleById(ID);

          debug('Reload for file: %s', file.replace(options.root, ''));

          return [module] as ModuleNode[];
        }
      }
    },
  };
}
Example #21
Source File: index.ts    From react-dev-inspector with MIT License 5 votes vote down vote up
inspectorServer = (): Plugin => ({
  name: 'inspector-server-plugin',
  configureServer(server) {
    server.middlewares.use(queryParserMiddleware)

    server.middlewares.use(launchEditorMiddleware)
  },
})
Example #22
Source File: index.ts    From vite-plugin-react with MIT License 5 votes vote down vote up
plugin: Plugin = {
  configureServer: reactRefreshServerPlugin,
  transforms: [reactRefreshTransform]
}
Example #23
Source File: index.ts    From convue with MIT License 5 votes vote down vote up
function routePlugin(userOptions: UserOptions = {}): Plugin {
  let config: ResolvedConfig | undefined;
  let filesPath: string[] = [];
  let generatedPlugins: any[] | null | undefined;

  const options: ResolvedOptions = resolveOptions(userOptions);

  return {
    name: 'vite-plugin-store',
    enforce: 'pre',
    configResolved(_config) {
      config = _config;
      options.root = config.root;
      options.pluginsDirPath = normalizePath(resolve(config.root, options.dir));
      debug('pluginsDirPath', options.pluginsDirPath);
    },
    resolveId(id) {
      if (id === ID) return ID;
    },
    async load(id) {
      if (id === ID) {
        debug('Loading files...');

        filesPath = await getStoresPath(options);

        debug('FilesPath: %O', filesPath);

        if (!generatedPlugins) generatedPlugins = generatePlugins(filesPath, options);

        debug('Components: %O', generatedPlugins);

        const clientCode = generateClientCode(generatedPlugins);

        debug('Client code: %O', clientCode)

        return clientCode;
      }
    },
    async handleHotUpdate({ file, server }) {
      const extensionsRE = new RegExp(`\\.(${options.extensions.join('|')})$`);
      const storeDir = options.dir;
      const pluginsDirPath = options.pluginsDirPath;
      // Handle pages HMR
      if (
        (file.startsWith(pluginsDirPath) || file.startsWith(pluginsDirPath)) &&
        extensionsRE.test(file)
      ) {
        let needReload = false;

        // HMR on new file created
        // Otherwise, handle HMR from custom block
        if (file.includes(storeDir)) {
          if (
            !filesPath.includes(file.replace(`${pluginsDirPath}/`, ''))
          ) {
            generatedPlugins = null;
            needReload = true;
          }
        }

        if (needReload) {
          const { moduleGraph } = server;
          const module = moduleGraph.getModuleById(ID);

          debug('Reload for file: %s', file.replace(options.root, ''));

          return [module] as ModuleNode[];
        }
      }
    },
  };
}
Example #24
Source File: retrieveDevServer.ts    From telefunc with MIT License 5 votes vote down vote up
function retrieveDevServer(): Plugin {
  return {
    name: 'telefunc:retrieveDevServer',
    configureServer(viteDevServer) {
      globalContext.viteDevServer = viteDevServer
    }
  } as Plugin
}
Example #25
Source File: create-vite-config.ts    From netless-app with MIT License 5 votes vote down vote up
export function createViteConfig({
  entry = path.resolve(process.cwd(), "src/index.ts"),
  name,
  formats = ["es", "cjs", "iife"],
}: {
  entry?: string;
  name?: string;
  formats?: LibraryFormats[];
} = {}): UserConfigFn {
  return defineConfig(({ mode }) => {
    const isProd = mode === "production";
    const pkgName = (entry.match(/packages[/\\]([^/\\]+)/) || ["", ""])[1];

    if (!pkgName) {
      throw new Error(`can not find package from ${entry}`);
    }

    const varName = pkgName
      .split(/-+/)
      .map((e: string) => e[0].toUpperCase() + e.slice(1))
      .join("");

    const pkg = findPackageJSON(entry);

    return {
      define: {
        __APP_VERSION__: pkg ? JSON.stringify(pkg.version) : "undefined",
      },
      plugins: [
        svelte({
          emitCss: false,
          experimental: {
            useVitePreprocess: true,
          },
        }),
      ],
      build: {
        lib: {
          entry,
          formats,
          fileName: "main",
          name: name || "Netless" + varName,
        },
        sourcemap: isProd,
        outDir: "dist",
        rollupOptions: {
          external: ["@netless/window-manager"],
          output: {
            manualChunks: undefined,
            inlineDynamicImports: true,
            exports: "named",
          },
          plugins: [peerDepsExternal() as Plugin],
        },
        minify: isProd,
      },
    };
  }) as UserConfigFn;
}
Example #26
Source File: plugin.ts    From vite-ssr with MIT License 5 votes vote down vote up
function hasPlugin(plugins: Plugin[] | Plugin[][] = [], name: string): boolean {
  return !!plugins.flat().find((plugin) => (plugin.name || '').startsWith(name))
}
Example #27
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
export default function cssForceModulesPlugin({enableModules = DEFAULT_ENABLE_MODULES}: Options = {}): Plugin {
    const root = {value: process.cwd()};

    return {
        name: 'reskript:css-force-modules',
        async configResolved(config) {
            root.value = config.root;
        },
        enforce: 'pre',
        async resolveId(source, importer, options) {
            const resolved = await this.resolve(source, importer, {...options, skipSelf: true});

            if (!resolved || !enableModules(resolved.id)) {
                return;
            }

            // 我至今没搞懂Vite什么时候会加上`?used`这一段
            const id = resolved.id.replace(/\?used$/, '');
            const extension = path.extname(id);

            if (requireForceModules(id)) {
                const searchSplitIndex = resolved.id.lastIndexOf('?');
                const search = searchSplitIndex < 0 ? '' : resolved.id.slice(searchSplitIndex);
                // 因为类似LESS这样的预处理器是要处理样式中的`@import`的,这些引入的文件查找并不完全走Vite的规则,
                // 为了让预处理器能正确地找到对应的文件和,我们必须保持当前文件的`id`在修改后能保留原始的目录信息,
                // 即`path.dirname(resolved.id)`和`path.dirname(source)`是一样的。
                // 因此,我们不能按照Vite推荐的方法,在这里用`virturl:xxx`这样的虚拟路径,只能在原路径上做处理。
                return `${id}${VIRTUAL_ID_PADDING}.module${extension}${search}`;
            }
        },
        async load(id) {
            if (!id.includes(VIRTUAL_ID_PADDING)) {
                return;
            }

            const extension = path.extname(id);
            const file = id.slice(0, -(VIRTUAL_ID_PADDING.length + `.module${extension}`.length));
            // 不知道为什么,这个路径在测试的时候是硬盘上的绝对路径,在实际用的时候是基于`root`的相对路径
            const code = await fs.readFile(file.startsWith(root.value) ? file : path.join(root.value, file), 'utf-8');
            return code;
        },
    };
}
Example #28
Source File: plugin.ts    From vite-dts with MIT License 5 votes vote down vote up
export default function dts(): Plugin {
  return {
    name: 'vite:dts',
    apply: 'build',
    async configResolved(config) {
      const { logger } = config
      const { outDir } = config.build

      const { entry, formats = ['es'] } = config.build.lib || {}
      if (!entry) {
        return logger.warn(
          `[vite-dts] Expected "build.lib.entry" to exist in vite config`
        )
      }

      const pkg = await loadJSON<any>(path.join(config.root, 'package.json'))

      if (!pkg.main && formats.includes('cjs')) {
        return logger.warn(
          `[vite-dts] Expected "main" to exist in package.json`
        )
      }
      if (!pkg.module && formats.includes('es')) {
        return logger.warn(
          `[vite-dts] Expected "module" to exist in package.json`
        )
      }

      const entryPath = path.resolve(config.root, entry)
      const entryImportPath = path.relative(
        path.resolve(config.root, outDir),
        entryPath.replace(/\.tsx?$/, '')
      )

      const posixEntryImportPath = entryImportPath.split(path.sep).join(path.posix.sep)

      const entryImpl = fs.readFileSync(entryPath, 'utf8')
      const hasDefaultExport =
        /^(export default |export \{[^}]+? as default\s*[,}])/m.test(entryImpl)

      const dtsModule =
        `export * from "${posixEntryImportPath}"` +
        (hasDefaultExport ? `\nexport {default} from "${posixEntryImportPath}"` : ``)

      const cjsModulePath = path.relative(outDir, pkg.main)
      const esModulePath = path.relative(outDir, pkg.module)

      this.generateBundle = function ({ entryFileNames }) {
        if (entryFileNames == cjsModulePath) {
          this.emitFile({
            type: 'asset',
            fileName: cjsModulePath.replace(/\.js$/, '.d.ts'),
            source: dtsModule,
          })
        } else if (entryFileNames == esModulePath) {
          this.emitFile({
            type: 'asset',
            fileName: esModulePath.replace(/\.js$/, '.d.ts'),
            source: dtsModule,
          })
        }
      }
    },
  }
}
Example #29
Source File: index.ts    From vite-plugin-md-preview with MIT License 5 votes vote down vote up
export function MarkdownVuePreview(options: MarkdownVuePreviewOptions = {}): PluginOption[] {
  const { highlighter, shiki: shikiOptions } = options

  const plugin: Plugin = {
    name: 'vite:md-vue',
    enforce: 'pre',
    async configResolved(config) {
      const shiki = await getHighlighter({
        theme: 'github-light',
        langs: ['vue'],
        ...shikiOptions,
      })
      transformOptions.highlighter =
        highlighter ||
        ((code: string) => {
          return shiki.codeToHtml(code, { lang: 'vue' })
        })
      transformOptions.root = config.root
      // vuePlugin = resolvedConfig.plugins.find((p) => p.name === 'vite:vue');
    },
    resolveId(id) {
      if (VUE_CODE_REGEXP.test(id)) {
        return `${id}`
      }
    },
    load(id) {
      if (VUE_CODE_REGEXP.test(id)) {
        const code = vueBlockMap.get(id)
        return code
      }
    },
    async handleHotUpdate(ctx) {
      const { file, server } = ctx
      const { moduleGraph, ws } = server

      if (/\.md$/.test(file)) {
        const updates: Update[] = []
        for (const [name] of vueBlockMap) {
          const mods = [...(moduleGraph.getModulesByFile(name) || new Set())]
          moduleGraph.onFileChange(name)
          // console.log(mods);
          for (const mod of mods) {
            updates.push({
              type: `js-update`,
              timestamp: mod.lastInvalidationTimestamp,
              path: `${mod.url}`,
              acceptedPath: `${mod.url}`,
            })
          }
        }
        ws.send({
          type: 'update',
          updates,
        })
      }
    },
  }

  return [plugin]
}