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

feat: library mode does not include preload #4097

Merged
merged 2 commits into from Jul 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/playground/lib/__tests__/lib.spec.ts
@@ -1,4 +1,6 @@
import { isBuild } from 'testUtils'
import { isBuild, findAssetFile, testDir } from 'testUtils'
import path from 'path'
import fs from 'fs'

if (isBuild) {
test('es', async () => {
Expand All @@ -8,6 +10,15 @@ if (isBuild) {
test('umd', async () => {
expect(await page.textContent('.umd')).toBe('It works')
})

test('Library mode does not include `preload`', async () => {
expect(await page.textContent('.dynamic-import-message')).toBe('hello vite')
const code = fs.readFileSync(
path.join(testDir, 'dist/lib/dynamic-import-message.js'),
'utf-8'
)
expect(code).not.toMatch('__vitePreload')
})
} else {
test('dev', async () => {
expect(await page.textContent('.demo')).toBe('It works')
Expand Down
90 changes: 90 additions & 0 deletions packages/playground/lib/__tests__/serve.js
@@ -0,0 +1,90 @@
// @ts-check
// this is automtically detected by scripts/jestPerTestSetup.ts and will replace
// the default e2e test serve behavior

const path = require('path')
const http = require('http')
const sirv = require('sirv')

const port = (exports.port = 9527)

/**
* @param {string} root
* @param {boolean} isBuildTest
*/
exports.serve = async function serve(root, isBuildTest) {
// build first

if (!isBuildTest) {
const { createServer } = require('vite')
process.env.VITE_INLINE = 'inline-serve'
let viteServer = await (
await createServer({
root: root,
logLevel: 'silent',
server: {
watch: {
usePolling: true,
interval: 100
},
host: true,
fs: {
strict: !isBuildTest
}
},
build: {
target: 'esnext'
}
})
).listen()
// use resolved port/base from server
const base = viteServer.config.base === '/' ? '' : viteServer.config.base
const url =
(global.viteTestUrl = `http://localhost:${viteServer.config.server.port}${base}`)
await page.goto(url)

return viteServer
} else {
const { build } = require('vite')
await build({
root,
logLevel: 'silent',
configFile: path.resolve(__dirname, '../vite.config.js')
})

await build({
root,
logLevel: 'silent',
configFile: path.resolve(__dirname, '../vite.dyimport.config.js')
})

// start static file server
const serve = sirv(path.resolve(root, 'dist'))
const httpServer = http.createServer((req, res) => {
if (req.url === '/ping') {
res.statusCode = 200
res.end('pong')
} else {
serve(req, res)
}
})

return new Promise((resolve, reject) => {
try {
const server = httpServer.listen(port, async () => {
await page.goto(`http://localhost:${port}`)
resolve({
// for test teardown
async close() {
await new Promise((resolve) => {
server.close(resolve)
})
}
})
})
} catch (e) {
reject(e)
}
})
}
}
7 changes: 7 additions & 0 deletions packages/playground/lib/index.dist.html
@@ -1,13 +1,20 @@
<!-- the production demo page, copied into dist/ -->
<div class="es"></div>
<div class="umd"></div>
<div class="dynamic-import-message"></div>

<script type="module">
import myLib from './my-lib-custom-filename.es.js'

myLib('.es')
</script>

<script type="module">
import message from './lib/dynamic-import-message.js'

message('.dynamic-import-message')
</script>

<script src="./my-lib-custom-filename.umd.js"></script>
<script>
MyLib('.umd')
Expand Down
4 changes: 4 additions & 0 deletions packages/playground/lib/src/main2.js
@@ -0,0 +1,4 @@
export default async function message(sel) {
const message = await import('./message.js')
document.querySelector(sel).textContent = message.default
}
1 change: 1 addition & 0 deletions packages/playground/lib/src/message.js
@@ -0,0 +1 @@
export default 'hello vite'
18 changes: 18 additions & 0 deletions packages/playground/lib/vite.dyimport.config.js
@@ -0,0 +1,18 @@
const fs = require('fs')
const path = require('path')

/**
* @type {import('vite').UserConfig}
*/
module.exports = {
build: {
minify: false,
lib: {
entry: path.resolve(__dirname, 'src/main2.js'),
formats: ['es'],
name: 'message',
fileName: () => 'dynamic-import-message.js'
},
outDir: 'dist/lib'
}
}
4 changes: 2 additions & 2 deletions packages/vite/src/node/importGlob.ts
Expand Up @@ -15,7 +15,7 @@ export async function transformImportGlob(
importIndex: number,
root: string,
normalizeUrl?: (url: string, pos: number) => Promise<[string, string]>,
ssr = false
preload = true
): Promise<{
importsString: string
imports: string[]
Expand Down Expand Up @@ -87,7 +87,7 @@ export async function transformImportGlob(
entries += ` ${JSON.stringify(file)}: ${identifier},`
} else {
let imp = `import(${JSON.stringify(importee)})`
if (!normalizeUrl && !ssr) {
if (!normalizeUrl && preload) {
imp =
`(${isModernFlag}` +
`? ${preloadMethod}(()=>${imp},"${preloadMarker}")` +
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -82,6 +82,7 @@ function preload(baseModule: () => Promise<{}>, deps?: string[]) {
*/
export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
const ssr = !!config.build.ssr
const insertPreload = !(ssr || !!config.build.lib)

return {
name: 'vite:import-analysis',
Expand Down Expand Up @@ -145,7 +146,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
index,
config.root,
undefined,
ssr
insertPreload
)
str().prepend(importsString)
str().overwrite(expStart, endIndex, exp)
Expand All @@ -155,7 +156,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
continue
}

if (dynamicIndex > -1 && !ssr) {
if (dynamicIndex > -1 && insertPreload) {
needPreloadHelper = true
const dynamicEnd = source.indexOf(`)`, end) + 1
const original = source.slice(dynamicIndex, dynamicEnd)
Expand All @@ -166,7 +167,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

if (
needPreloadHelper &&
!ssr &&
insertPreload &&
!source.includes(`const ${preloadMethod} =`)
) {
str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`)
Expand Down