Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using createServer and trying to build in lib mode gives "[vite:worker-import-meta-url] can not match string template expression." error #8014

Closed
7 tasks done
kpturner opened this issue May 4, 2022 · 3 comments · Fixed by #8054

Comments

@kpturner
Copy link

kpturner commented May 4, 2022

Describe the bug

I want to build a TS file in lib mode for production. The code includes the use of the createServer module from Vite. When I try to build it, the build crashes

vite v2.9.5 building for production...
✓ 18 modules transformed.
[vite:worker-import-meta-url] can not match string template expression.
file: /Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js
error during build:
Error: can not match string template expression.
    at error$3 (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26769:17)
    at lexStringTemplateExpression (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26764:9)
    at emptyString (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26685:28)
    at Object.transform (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:60804:37)
    at /Users/kpturner/fotech/vite-bug-minimal/node_modules/rollup/dist/shared/rollup.js:22823:37

Reproduction

https://github.com/kpturner/vite-bug-minimal

System Info

System:
    OS: macOS 11.6.4
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 2.37 GB / 16.00 GB
    Shell: 5.8 - /usr/local/bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.1/bin/npm
  Browsers:
    Chrome: 100.0.4896.127
    Edge: 100.0.1185.39
    Firefox: 96.0.3
    Safari: 15.3
  npmPackages:
    vite: 2.9.5 => 2.9.5

Used Package Manager

npm

Logs

vite:config bundled config file loaded in 70.52ms +0ms
  vite:config using resolved config: {
  vite:config   plugins: [
  vite:config     'vite:build-metadata',
  vite:config     'alias',
  vite:config     'vite:modulepreload-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html-inline-proxy',
  vite:config     'vite:css',
  vite:config     'vite:esbuild',
  vite:config     'vite:json',
  vite:config     'vite:wasm',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:build-html',
  vite:config     'vite:worker-import-meta-url',
  vite:config     'vite:watch-package-data',
  vite:config     'commonjs',
  vite:config     'vite:data-uri',
  vite:config     'rollup-plugin-dynamic-import-variables',
  vite:config     'vite:asset-import-meta-url',
  vite:config     'vite:build-import-analysis',
  vite:config     'vite:esbuild-transpile',
  vite:config     'vite:reporter',
  vite:config     'vite:load-fallback'
  vite:config   ],
  vite:config   resolve: { dedupe: undefined, alias: [ [Object], [Object], [Object] ] },
  vite:config   build: {
  vite:config     target: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
  vite:config     polyfillModulePreload: true,
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: false,
  vite:config     cssTarget: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
  vite:config     sourcemap: false,
  vite:config     rollupOptions: { output: {} },
  vite:config     minify: false,
  vite:config     terserOptions: {},
  vite:config     write: true,
  vite:config     emptyOutDir: false,
  vite:config     manifest: false,
  vite:config     lib: {
  vite:config       entry: '/Users/kpturner/fotech/vite-bug-minimal/server.ts',
  vite:config       name: 'EntryServer',
  vite:config       fileName: [Function: fileName]
  vite:config     },
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     reportCompressedSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null,
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] }
  vite:config   },
  vite:config   configFile: '/Users/kpturner/fotech/vite-bug-minimal/vite.config.ts',
  vite:config   configFileDependencies: [ '/Users/kpturner/fotech/vite-bug-minimal/vite.config.ts' ],
  vite:config   inlineConfig: {
  vite:config     root: undefined,
  vite:config     base: undefined,
  vite:config     mode: undefined,
  vite:config     configFile: './vite.config.ts',
  vite:config     logLevel: undefined,
  vite:config     clearScreen: undefined,
  vite:config     build: {}
  vite:config   },
  vite:config   root: '/Users/kpturner/fotech/vite-bug-minimal',
  vite:config   base: '/',
  vite:config   publicDir: '/Users/kpturner/fotech/vite-bug-minimal/public',
  vite:config   cacheDir: '/Users/kpturner/fotech/vite-bug-minimal/node_modules/.vite',
  vite:config   command: 'build',
  vite:config   mode: 'production',
  vite:config   isWorker: false,
  vite:config   isProduction: true,
  vite:config   server: {
  vite:config     preTransformRequests: true,
  vite:config     fs: { strict: true, allow: [Array], deny: [Array] }
  vite:config   },
  vite:config   preview: {
  vite:config     port: undefined,
  vite:config     strictPort: undefined,
  vite:config     host: undefined,
  vite:config     https: undefined,
  vite:config     open: undefined,
  vite:config     proxy: undefined,
  vite:config     cors: undefined,
  vite:config     headers: undefined
  vite:config   },
  vite:config   env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
  vite:config   assetsInclude: [Function: assetsInclude],
  vite:config   logger: {
  vite:config     hasWarned: false,
  vite:config     info: [Function: info],
  vite:config     warn: [Function: warn],
  vite:config     warnOnce: [Function: warnOnce],
  vite:config     error: [Function: error],
  vite:config     clearScreen: [Function: clearScreen],
  vite:config     hasErrorLogged: [Function: hasErrorLogged]
  vite:config   },
  vite:config   packageCache: Map(0) { set: [Function (anonymous)] },
  vite:config   createResolver: [Function: createResolver],
  vite:config   optimizeDeps: {
  vite:config     esbuildOptions: { keepNames: undefined, preserveSymlinks: undefined }
  vite:config   },
  vite:config   worker: {
  vite:config     format: 'iife',
  vite:config     plugins: [
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object]
  vite:config     ],
  vite:config     rollupOptions: {}
  vite:config   }
  vite:config } +13ms
vite v2.9.5 building for production...
✓ 18 modules transformed.
[vite:worker-import-meta-url] can not match string template expression.
file: /Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js
error during build:
Error: can not match string template expression.
    at error$3 (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26769:17)
    at lexStringTemplateExpression (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26764:9)
    at emptyString (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:26685:28)
    at Object.transform (/Users/kpturner/fotech/vite-bug-minimal/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:60804:37)
    at /Users/kpturner/fotech/vite-bug-minimal/node_modules/rollup/dist/shared/rollup.js:22823:37

Validations

@bluwy
Copy link
Member

bluwy commented May 4, 2022

Looks like you're trying to use Vite to bundle Vite, sounds like a tricky and niche thing to fix. And may be best to use a separate esbuild/rollup script to workaround at the meantime. Curious to know what you're doing bundling a dev server though.

@kpturner
Copy link
Author

kpturner commented May 4, 2022

Yes the cutdown repo makes it look a bit odd.

The main full repo is using SSR and has a top level module (in Typescript) that builds everything (a fuller example below). It comes from the SSR examples. When I run that module I run it with ts-node in development, but I have a requirement to transpile it into JavaScript in production. I have done this easily enough with tsc but I would rather not use that AND Vite, so I am trying to get a transpiled version created by Vite. The problem is that the module is written to work in dev and prod mode, but will only be transpiled in prod mode where the code in question is redundant.

// @ts-check
import Bunyan from 'bunyan';
import compression from 'compression';
import Config from 'config';
import Express from 'express';
import fs from 'fs';
import http from 'http';
import path from 'path';
import serveStatic from 'serve-static';
import { createServer as createViteServer, ViteDevServer } from 'vite';
import { WebSocketServer } from 'ws';

// Websocket service (ours)
import WSServer from './src/wsserver/wsserver';

const log = Bunyan.createLogger({
    name: Config.get<string>('log.name'),
    level: Config.get<Bunyan.LogLevel>('log.level'),
    serializers: Bunyan.stdSerializers,
    streams: Config.get<Bunyan.Stream[]>('log.streams'),
    src: true
});

const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD;
const port = Config.get<number>('server.port');
let pathRoot = './dist/';
if (path.basename(__dirname) === 'dist') {
    pathRoot = './';
}

async function createServer(
    root = process.cwd(),
    isProd = process.env.NODE_ENV === 'production'
) {
    const resolve = (p: string) => {
        return path.resolve(__dirname, p).replace('dist/dist/', 'dist/');
    };
    const indexProd = isProd
        ? fs.readFileSync(resolve('dist/client/index.html'), 'utf-8')
        : '';

    const manifest = isProd
        ? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        require(`${pathRoot}client/ssr-manifest.json`)
        : {};

    const app = Express();

    /**
     * @type {import('vite').ViteDevServer}
     */
    let vite: ViteDevServer = {} as ViteDevServer;
    if (!isProd) {
        vite = await createViteServer({
            root,
            logLevel: isTest ? 'error' : 'info',
            server: {
                middlewareMode: 'ssr',
                watch: {
                    // During tests we edit the files too fast and sometimes chokidar
                    // misses change events, so enforce polling for consistency
                    usePolling: true,
                    interval: 100
                }
            }
        });
        // use vite's connect instance as middleware
        app.use(vite.middlewares);
    } else {
        app.use(compression());
        app.use(
            serveStatic(resolve('dist/client'), {
                index: false
            })
        );
    }

    app.use('*', async (req, res) => {
        try {
            const url = req.originalUrl;

            let template, render;
            if (!isProd) {
                // always read fresh template in dev
                template = fs.readFileSync(resolve('index.html'), 'utf-8');
                template = await vite.transformIndexHtml(url, template);
                render = (await vite.ssrLoadModule('/src/entry-server.ts')).render;
            } else {
                template = indexProd;
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                // eslint-disable-next-line @typescript-eslint/no-var-requires
                render = require(`${pathRoot}server/entry-server.js`).render;
            }

            const [appHtml, preloadLinks] = await render(url, manifest);

            const html = template
                .replace('<!--preload-links-->', preloadLinks)
                .replace('<!--app-html-->', appHtml);

            res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
        } catch (e) {
            if (vite && vite.ssrFixStacktrace) {
                vite.ssrFixStacktrace(e as Error);
            }
            console.log((e as Error).stack);
            res.status(500).end((e as Error).stack);
        }
    });

    const server = http.createServer(app);
    const wss = new WebSocketServer({ clientTracking: false, noServer: true });

    server.on('upgrade', function (request, socket, head) {

        log.debug('Connection upgraded successfully');

        wss.handleUpgrade(request, socket, head, function (ws) {
            wss.emit('connection', ws, request);
        });

    });

    wss.on('connection', function (ws, _request) {
        log.debug('Connected');
        new WSServer( { config: Config, log, ws } );
    });

    return { server, vite };
}

if (!isTest) {
    createServer().then(({ server }) =>
        server.listen(port, () => {
            const status = `Listening on http://localhost:${port}`;
            log.info(status);
            if (process.env.NODE_ENV === 'production') {
                console.log(status);
            }
        })
    );
}

// for test use
exports.createServer = createServer;

@usercao
Copy link

usercao commented May 7, 2022

const theme: 'light' | 'dark' = 'dark'
<img
  src={new URL(`/src/assets/images/star_big_${theme}.svg`, import.meta.url).href}
  alt="icon"
/>

@patak-dev @sapphi-red @poyoho I also had the above problems when I was in bulid. The impact of the project is very serious and extensive. Now I can't build normally. I hope you can have a look as soon as possible. Thank you very much for your repair.

@poyoho poyoho linked a pull request May 7, 2022 that will close this issue
9 tasks
@github-actions github-actions bot locked and limited conversation to collaborators May 22, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants