提交 c037dbfa 编写于 作者: fxy060608's avatar fxy060608

feat(cli): add chunkFileNames

上级 26941de2
......@@ -32,7 +32,7 @@
"peerDependencies": {
"@dcloudio/uni-cli-shared": "^3.0.0",
"@dcloudio/uni-shared": "^3.0.0",
"vite": "^2.0.0-beta.60"
"vite": "^2.0.0-beta.61"
},
"devDependencies": {
"@types/sass": "^1.16.0"
......
// import path from 'path'
// import fs from 'fs-extra'
import { Plugin } from 'rollup'
// const publicDir = '/Users/fxy/Documents/demo/my-vite-uniapp-project/src/static'
// const outDir = '/Users/fxy/Documents/demo/my-vite-uniapp-project/static'
export const buildPluginCopy: Plugin = {
name: 'uni:copy',
async generateBundle() {
// https://github.com/vitejs/vite/blob/master/src/node/build/index.ts#L621
// setTimeout(async () => {
// if (fs.existsSync(publicDir)) {
// for (const file of await fs.readdir(publicDir)) {
// await fs.copy(path.join(publicDir, file), path.resolve(outDir, file))
// }
// }
// }, 100)
},
}
import { Plugin } from 'rollup'
export const buildPluginDynamicImport: Plugin = {
name: 'uni:dynamic-import-polyfill',
renderDynamicImport() {
return {
left: 'dynamicImportPolyfill(',
right: ')',
}
},
}
import { sep } from 'path'
import { Plugin, AcornNode } from 'rollup'
import {
BaseNode,
Program,
Property,
Identifier,
MemberExpression,
MethodDefinition,
ExportSpecifier,
} from 'estree'
import {
attachScopes,
createFilter,
makeLegalIdentifier,
} from '@rollup/pluginutils'
import { walk } from 'estree-walker'
import MagicString from 'magic-string'
interface Scope {
parent: Scope
contains: (name: string) => boolean
}
type Injectment = string | [string, string]
export interface InjectOptions {
include?: string | RegExp | ReadonlyArray<string | RegExp> | null
exclude?: string | RegExp | ReadonlyArray<string | RegExp> | null
sourceMap?: boolean
[str: string]: Injectment | InjectOptions['include'] | Boolean
}
const escape = (str: string) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
const isProperty = (node: BaseNode): node is Property =>
node.type === 'Property'
const isIdentifier = (node: BaseNode): node is Identifier =>
node.type === 'Identifier'
const isMemberExpression = (node: BaseNode): node is MemberExpression =>
node.type === 'MemberExpression'
const isMethodDefinition = (node: BaseNode): node is MethodDefinition =>
node.type === 'MethodDefinition'
const isExportSpecifier = (node: BaseNode): node is ExportSpecifier =>
node.type === 'ExportSpecifier'
const isReference = (node: BaseNode, parent: BaseNode): boolean => {
if (isMemberExpression(node)) {
return !node.computed && isReference(node.object, node)
}
if (isIdentifier(node)) {
if (isMemberExpression(parent))
return parent.computed || node === parent.object
// `bar` in { bar: foo }
if (isProperty(parent) && node !== parent.value) return false
// `bar` in `class Foo { bar () {...} }`
if (isMethodDefinition(parent)) return false
// `bar` in `export { foo as bar }`
if (isExportSpecifier(parent) && node !== parent.local) return false
return true
}
return false
}
const flatten = (startNode: BaseNode) => {
const parts = []
let node = startNode
while (isMemberExpression(node)) {
parts.unshift((node.property as Identifier).name)
node = node.object
}
const { name } = node as Identifier
parts.unshift(name)
return { name, keypath: parts.join('.') }
}
function normalizeModulesMap(
modulesMap: Map<string, string | [string, string]>
) {
modulesMap.forEach((mod, key) => {
modulesMap.set(
key,
Array.isArray(mod)
? [mod[0].split(sep).join('/'), mod[1]]
: mod.split(sep).join('/')
)
})
}
function inject(options: InjectOptions) {
if (!options) throw new Error('Missing options')
const filter = createFilter(options.include, options.exclude)
const modules = Object.assign({}, options) as { [str: string]: Injectment }
delete modules.include
delete modules.exclude
delete modules.sourceMap
const modulesMap = new Map<string, string | [string, string]>()
const namespaceModulesMap = new Map<string, string | [string, string]>()
Object.keys(modules).forEach((name) => {
if (name.endsWith('.')) {
namespaceModulesMap.set(name, modules[name])
}
modulesMap.set(name, modules[name])
})
const hasNamespace = namespaceModulesMap.size > 0
// Fix paths on Windows
if (sep !== '/') {
normalizeModulesMap(modulesMap)
normalizeModulesMap(namespaceModulesMap)
}
const firstpass = new RegExp(
`(?:${Array.from(modulesMap.keys()).map(escape).join('|')})`,
'g'
)
const sourceMap = options.sourceMap !== false
return {
name: 'uni:inject',
transform(code, id) {
if (!filter(id)) return null
if (code.search(firstpass) === -1) return null
if (sep !== '/') id = id.split(sep).join('/')
let ast = null
try {
ast = (this.parse(code) as unknown) as Program
} catch (err) {
this.warn({
code: 'PARSE_ERROR',
message: `plugin-inject: failed to parse ${id}. Consider restricting the plugin to particular files via options.include`,
})
}
if (!ast) {
return null
}
const imports = new Set()
ast.body.forEach((node) => {
if (node.type === 'ImportDeclaration') {
node.specifiers.forEach((specifier) => {
imports.add(specifier.local.name)
})
}
})
// analyse scopes
let scope = attachScopes(ast, 'scope') as Scope
const magicString = new MagicString(code)
const newImports = new Map()
function handleReference(node: BaseNode, name: string, keypath: string) {
let mod = modulesMap.get(keypath)
if (!mod && hasNamespace) {
const mods = keypath.split('.')
if (mods.length === 2) {
mod = namespaceModulesMap.get(mods[0] + '.')
if (mod) {
mod = [mod as string, mods[1]]
}
}
}
if (mod && !imports.has(name) && !scope.contains(name)) {
if (typeof mod === 'string') mod = [mod, 'default']
if (mod[0] === id) return false
const hash = `${keypath}:${mod[0]}:${mod[1]}`
const importLocalName =
name === keypath ? name : makeLegalIdentifier(`$inject_${keypath}`)
if (!newImports.has(hash)) {
if (mod[1] === '*') {
newImports.set(
hash,
`import * as ${importLocalName} from '${mod[0]}';`
)
} else {
newImports.set(
hash,
`import { ${mod[1]} as ${importLocalName} } from '${mod[0]}';`
)
}
}
if (name !== keypath) {
magicString.overwrite(
(node as AcornNode).start,
(node as AcornNode).end,
importLocalName,
{
storeName: true,
}
)
}
return true
}
return false
}
walk(ast, {
enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation((node as AcornNode).start)
magicString.addSourcemapLocation((node as AcornNode).end)
}
if ((node as any).scope) {
scope = (node as any).scope
}
if (isProperty(node) && node.shorthand) {
const { name } = node.key as Identifier
handleReference(node, name, name)
this.skip()
return
}
if (isReference(node, parent)) {
const { name, keypath } = flatten(node)
const handled = handleReference(node, name, keypath)
if (handled) {
this.skip()
}
}
},
leave(node) {
if ((node as any).scope) {
scope = scope.parent
}
},
})
if (newImports.size === 0) {
return {
code,
ast,
map: sourceMap ? magicString.generateMap({ hires: true }) : null,
}
}
const importBlock = Array.from(newImports.values()).join('\n\n')
magicString.prepend(`${importBlock}\n\n`)
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap({ hires: true }) : null,
}
},
} as Plugin
}
export const buildPluginInject: Plugin = inject({
exclude: /\.[n]?vue$/,
'__GLOBAL__.': '@dcloudio/uni-h5',
'uni.': '@dcloudio/uni-h5',
getApp: ['@dcloudio/uni-h5', 'getApp'],
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages'],
UniServiceJSBridge: ['@dcloudio/uni-h5', 'UniServiceJSBridge'],
})
export * from './buildPluginCopy'
export * from './buildPluginInject'
export * from './buildPluginDynamicImport'
import path from 'path'
import slash from 'slash'
import { UserConfig } from 'vite'
import { VitePluginUniResolvedOptions } from '..'
export function createBuild(
options: VitePluginUniResolvedOptions
): UserConfig['build'] {
return {
rollupOptions: {
output: {
chunkFileNames(chunkInfo) {
if (chunkInfo.facadeModuleId) {
const dirname = path.relative(
options.inputDir,
path.dirname(chunkInfo.facadeModuleId)
)
if (dirname) {
return `${options.assetsDir}/${slash(dirname).replace(
/\//g,
'-'
)}-[name].[hash].js`
}
}
return '[name].[hash].js'
},
},
},
}
}
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '..'
import { createCss } from './css'
import { createAlias } from './alias'
import { createDefine } from './define'
import { createServer } from './server'
import { createBuild } from './build'
import { createOptimizeDeps } from './optimizeDeps'
import { createCss } from './css'
export function createConfig(
options: VitePluginUniResolvedOptions
......@@ -16,6 +17,7 @@ export function createConfig(
alias: createAlias(options),
optimizeDeps: createOptimizeDeps(options),
server: createServer(options),
build: createBuild(options),
css: createCss(options),
}
}
......
......@@ -8,6 +8,7 @@ export function createConfigResolved(options: VitePluginUniResolvedOptions) {
return ((config) => {
options.root = config.root
options.inputDir = path.resolve(config.root, 'src')
options.assetsDir = config.build.assetsDir
resolvePlugins((config as unknown) as UserConfig, options)
}) as Plugin['configResolved']
}
......@@ -14,6 +14,7 @@ export interface VitePluginUniOptions {
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
root: string
inputDir: string
assetsDir: string
devServer?: ViteDevServer
}
......@@ -25,6 +26,7 @@ export default function uniPlugin(
const options: VitePluginUniResolvedOptions = {
...rawOptions,
root: process.cwd(),
assetsDir: 'assets',
inputDir: rawOptions.inputDir || path.resolve(process.cwd(), 'src'),
}
initEnv(options)
......
......@@ -812,35 +812,35 @@
"@types/yargs-parser" "*"
"@typescript-eslint/parser@^4.12.0":
version "4.14.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.14.1.tgz#3bd6c24710cd557d8446625284bcc9c6d52817c6"
integrity sha512-mL3+gU18g9JPsHZuKMZ8Z0Ss9YP1S5xYZ7n68Z98GnPq02pYNQuRXL85b9GYhl6jpdvUc45Km7hAl71vybjUmw==
version "4.14.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.14.2.tgz#31e216e4baab678a56e539f9db9862e2542c98d0"
integrity sha512-ipqSP6EuUsMu3E10EZIApOJgWSpcNXeKZaFeNKQyzqxnQl8eQCbV+TSNsl+s2GViX2d18m1rq3CWgnpOxDPgHg==
dependencies:
"@typescript-eslint/scope-manager" "4.14.1"
"@typescript-eslint/types" "4.14.1"
"@typescript-eslint/typescript-estree" "4.14.1"
"@typescript-eslint/scope-manager" "4.14.2"
"@typescript-eslint/types" "4.14.2"
"@typescript-eslint/typescript-estree" "4.14.2"
debug "^4.1.1"
"@typescript-eslint/scope-manager@4.14.1":
version "4.14.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.14.1.tgz#8444534254c6f370e9aa974f035ced7fe713ce02"
integrity sha512-F4bjJcSqXqHnC9JGUlnqSa3fC2YH5zTtmACS1Hk+WX/nFB0guuynVK5ev35D4XZbdKjulXBAQMyRr216kmxghw==
"@typescript-eslint/scope-manager@4.14.2":
version "4.14.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.14.2.tgz#64cbc9ca64b60069aae0c060b2bf81163243b266"
integrity sha512-cuV9wMrzKm6yIuV48aTPfIeqErt5xceTheAgk70N1V4/2Ecj+fhl34iro/vIssJlb7XtzcaD07hWk7Jk0nKghg==
dependencies:
"@typescript-eslint/types" "4.14.1"
"@typescript-eslint/visitor-keys" "4.14.1"
"@typescript-eslint/types" "4.14.2"
"@typescript-eslint/visitor-keys" "4.14.2"
"@typescript-eslint/types@4.14.1":
version "4.14.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.14.1.tgz#b3d2eb91dafd0fd8b3fce7c61512ac66bd0364aa"
integrity sha512-SkhzHdI/AllAgQSxXM89XwS1Tkic7csPdndUuTKabEwRcEfR8uQ/iPA3Dgio1rqsV3jtqZhY0QQni8rLswJM2w==
"@typescript-eslint/types@4.14.2":
version "4.14.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.14.2.tgz#d96da62be22dc9dc6a06647f3633815350fb3174"
integrity sha512-LltxawRW6wXy4Gck6ZKlBD05tCHQUj4KLn4iR69IyRiDHX3d3NCAhO+ix5OR2Q+q9bjCrHE/HKt+riZkd1At8Q==
"@typescript-eslint/typescript-estree@4.14.1":
version "4.14.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.14.1.tgz#20d3b8c8e3cdc8f764bdd5e5b0606dd83da6075b"
integrity sha512-M8+7MbzKC1PvJIA8kR2sSBnex8bsR5auatLCnVlNTJczmJgqRn8M+sAlQfkEq7M4IY3WmaNJ+LJjPVRrREVSHQ==
"@typescript-eslint/typescript-estree@4.14.2":
version "4.14.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.14.2.tgz#9c5ebd8cae4d7b014f890acd81e8e17f309c9df9"
integrity sha512-ESiFl8afXxt1dNj8ENEZT12p+jl9PqRur+Y19m0Z/SPikGL6rqq4e7Me60SU9a2M28uz48/8yct97VQYaGl0Vg==
dependencies:
"@typescript-eslint/types" "4.14.1"
"@typescript-eslint/visitor-keys" "4.14.1"
"@typescript-eslint/types" "4.14.2"
"@typescript-eslint/visitor-keys" "4.14.2"
debug "^4.1.1"
globby "^11.0.1"
is-glob "^4.0.1"
......@@ -848,12 +848,12 @@
semver "^7.3.2"
tsutils "^3.17.1"
"@typescript-eslint/visitor-keys@4.14.1":
version "4.14.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.14.1.tgz#e93c2ff27f47ee477a929b970ca89d60a117da91"
integrity sha512-TAblbDXOI7bd0C/9PE1G+AFo7R5uc+ty1ArDoxmrC1ah61Hn6shURKy7gLdRb1qKJmjHkqu5Oq+e4Kt0jwf1IA==
"@typescript-eslint/visitor-keys@4.14.2":
version "4.14.2"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.14.2.tgz#997cbe2cb0690e1f384a833f64794e98727c70c6"
integrity sha512-KBB+xLBxnBdTENs/rUgeUKO0UkPBRs2vD09oMRRIkj5BEN8PX1ToXV532desXfpQnZsYTyLLviS7JrPhdL154w==
dependencies:
"@typescript-eslint/types" "4.14.1"
"@typescript-eslint/types" "4.14.2"
eslint-visitor-keys "^2.0.0"
"@vitejs/plugin-vue@^1.0.4":
......@@ -1003,9 +1003,9 @@ ajv@^6.10.0, ajv@^6.12.3, ajv@^6.12.4:
uri-js "^4.2.2"
ajv@^7.0.2:
version "7.0.3"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-7.0.3.tgz#13ae747eff125cafb230ac504b2406cf371eece2"
integrity sha512-R50QRlXSxqXcQP5SvKUrw8VZeypvo12i2IX0EeR5PiZ7bEKeHWgzgo264LDadUsCU42lTJVhFikTqJwNeH34gQ==
version "7.0.4"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-7.0.4.tgz#827e5f5ae32f5e5c1637db61f253a112229b5e2f"
integrity sha512-xzzzaqgEQfmuhbhAoqjJ8T/1okb6gAzXn/eQRNpAN1AEUoHJTNF9xCDRTtf/s3SKldtZfa+RJeTs+BQq+eZ/sw==
dependencies:
fast-deep-equal "^3.1.1"
json-schema-traverse "^1.0.0"
......@@ -1982,9 +1982,9 @@ error-ex@^1.3.1:
is-arrayish "^0.2.1"
esbuild@^0.8.34:
version "0.8.38"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.8.38.tgz#04dc395e15c77bbc9d6798e9b31275546bcf7b9a"
integrity sha512-wSunJl8ujgBs9eVGubc8Y6fn/DkDjNyfQBVOFTY1E7sRxr8KTjmqyLIiE0M3Z4CjMnCu/rttCugwnOzY+HiwIw==
version "0.8.39"
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.8.39.tgz#18b84a3d56173c55ee8f45bc6c7b5374b0a98ecb"
integrity sha512-/do5H74a5ChyeKRWfkDh3EpICXpsz6dWTtFFbotb7BlIHvWqnRrZYDb8IBubOHdEtKzuiksilRO19aBtp3/HHQ==
escape-string-regexp@^1.0.5:
version "1.0.5"
......@@ -4827,9 +4827,9 @@ rollup-pluginutils@^2.3.1, rollup-pluginutils@^2.8.2:
estree-walker "^0.6.1"
rollup@^2.35.1:
version "2.38.3"
resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.38.3.tgz#2a0b6cc6eab1da4431aab875a31a401fa2988c10"
integrity sha512-FVx/XzR2DtCozKNDBjHJCHIgkC12rNg/ruAeoYWjLeeKfSKgwhh+lDLDhuCkuRG/fsup8py8dKBTlHdvUFX32A==
version "2.38.4"
resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.38.4.tgz#1b84ea8728c73b1a00a6a6e9c630ec8c3fe48cea"
integrity sha512-B0LcJhjiwKkTl79aGVF/u5KdzsH8IylVfV56Ut6c9ouWLJcUK17T83aZBetNYSnZtXf2OHD4+2PbmRW+Fp5ulg==
optionalDependencies:
fsevents "~2.3.1"
......@@ -5068,9 +5068,9 @@ source-map-support@^0.5.6, source-map-support@~0.5.19:
source-map "^0.6.0"
source-map-url@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3"
integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=
version "0.4.1"
resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.1.tgz#0af66605a745a5a2f91cf1bbf8a7afbc283dec56"
integrity sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw==
source-map@^0.5.0, source-map@^0.5.6:
version "0.5.7"
......@@ -5616,10 +5616,10 @@ verror@1.10.0:
core-util-is "1.0.2"
extsprintf "^1.2.0"
vite@^2.0.0-beta.60:
version "2.0.0-beta.60"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.0.0-beta.60.tgz#160d69968f29d05e0a4a22a6cc690d997fd793ea"
integrity sha512-B3qaJrSp0pbgjv2ROA7/0KRgJFs+QhH43OTo6Hau/dGopKotZFuE04FBRCjJ3+h0ePEH4DUG7+e2tUUgkywb0A==
vite@^2.0.0-beta.61:
version "2.0.0-beta.61"
resolved "https://registry.yarnpkg.com/vite/-/vite-2.0.0-beta.61.tgz#da605152999cf8943672202ab6b38b68f4c7b9e4"
integrity sha512-NyRZ7vCwtfw/z18HmFr5ZIesum26Dg9x4ykuit1YmYsZlPxx/oF3il1U6MqkXZD2wy8HaR5fQi9d9B/6vEJMbw==
dependencies:
esbuild "^0.8.34"
postcss "^8.2.1"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册