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

experimental: component options injection plugin #159

Merged
merged 2 commits into from
Feb 26, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ module.exports = {
'plugin:vue-libs/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended'
'plugin:prettier/recommended',
'prettier'
],
plugins: ['@typescript-eslint'],
parser: 'vue-eslint-parser',
Expand All @@ -30,6 +30,7 @@ module.exports = {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-non-null-assertion': 'off'
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/ban-ts-comment': 'off'
}
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@
"@types/loader-utils": "^2.0.0",
"@types/memory-fs": "^0.3.2",
"@types/node": "^14.14.10",
"@types/webpack": "^4.41.1",
"@types/webpack": "^4.41.26",
"@types/webpack-merge": "^4.1.5",
"@typescript-eslint/eslint-plugin": "^4.15.0",
"@typescript-eslint/parser": "^4.15.0",
"@vue/compiler-sfc": "^3.0.5",
"babel-loader": "^8.1.0",
"eslint": "^7.19.0",
"eslint-config-prettier": "^7.2.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue-libs": "^4.0.0",
"jest": "^26.6.3",
Expand All @@ -64,7 +64,7 @@
"vue": "^3.0.4",
"vue-i18n": "^9.0.0-rc.5",
"vue-loader": "^16.1.2",
"webpack": "^4.44.2",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^4.2.2"
Expand Down
23 changes: 23 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import webpack from 'webpack'

declare class IntlifyVuePlugin implements webpack.Plugin {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(optoins: Record<string, any>)
apply(compiler: webpack.Compiler): void
}

let Plugin: typeof IntlifyVuePlugin

console.warn(
`[@intlify/vue-i18n-loader] IntlifyVuePlugin is experimental! This plugin is used for Intlify tools. Don't use this plugin to enhancement Component options.`
)

if (webpack.version && webpack.version[0] > '4') {
// webpack5 and upper
Plugin = require('./pluginWebpack5').default // eslint-disable-line @typescript-eslint/no-var-requires
} else {
// webpack4 and lower
Plugin = require('./pluginWebpack4').default // eslint-disable-line @typescript-eslint/no-var-requires
}

export default Plugin
244 changes: 244 additions & 0 deletions src/pluginWebpack4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { parse as parseQuery } from 'querystring'
import webpack from 'webpack'
import { ReplaceSource } from 'webpack-sources'
import { isFunction, isObject, isRegExp, isString } from '@intlify/shared'
const Dependency = require('webpack/lib/Dependency') // eslint-disable-line @typescript-eslint/no-var-requires
// const Template = require('webpack/lib/Template') // eslint-disable-line @typescript-eslint/no-var-requires

const PLUGIN_ID = 'IntlifyVuePlugin'

interface NormalModule extends webpack.compilation.Module {
resource?: string
request?: string
userRequest?: string
addDependency(dep: unknown): void
parser?: webpack.compilation.normalModuleFactory.Parser
loaders?: Array<{
loader: string
options: any
indent?: string
type?: string
}>
}

type InjectionValues = Record<string, any>

class VueComponentDependency extends Dependency {
static Template: VueComponentDependencyTemplate
script?: NormalModule
templa?: NormalModule
values: InjectionValues
statement: any

constructor(
script: NormalModule | undefined,
template: NormalModule | undefined,
values: InjectionValues,
statement: any
) {
super()
this.script = script
this.template = template
this.values = values
this.statement = statement
}

updateHash(hash: any) {
super.updateHash(hash)
const scriptModule = this.script
hash.update(
(scriptModule &&
(!scriptModule.buildMeta || scriptModule.buildMeta.exportsType)) + ''
)
hash.update((scriptModule && scriptModule.id) + '')
const templateModule = this.templa
hash.update(
(templateModule &&
(!templateModule.buildMeta || templateModule.buildMeta.exportsType)) +
''
)
hash.update((templateModule && templateModule.id) + '')
}
}

/*
function getRequestAndIndex(
script: NormalModule,
template: NormalModule
): [string, number] {
if (script && template) {
return [script.userRequest!, 1]
} else if (script && !template) {
return [script.userRequest!, 0]
} else if (!script && template) {
return [template.userRequest!, 0]
} else {
return ['', -1]
}
}
*/

function stringifyObj(obj: Record<string, any>): string {
return `Object({${Object.keys(obj)
.map(key => {
const code = obj[key]
return `${JSON.stringify(key)}:${toCode(code)}`
})
.join(',')}})`
}

function toCode(code: any): string {
if (code === null) {
return 'null'
}

if (code === undefined) {
return 'undefined'
}

if (isString(code)) {
return JSON.stringify(code)
}

if (isRegExp(code) && code.toString) {
return code.toString()
}

if (isFunction(code) && code.toString) {
return '(' + code.toString() + ')'
}

if (isObject(code)) {
return stringifyObj(code)
}

return code + ''
}

function generateCode(dep: VueComponentDependency, importVar: string): string {
// const [request, index] = getRequestAndIndex(dep.script!, dep.template!)
// if (!require) {
// return ''
// }

// const importVar = `${Template.toIdentifier(
// `${request}`
// )}__WEBPACK_IMPORTED_MODULE_${index.toString()}__["default"]`

const injectionCodes = ['']
Object.keys(dep.values).forEach(key => {
const code = dep.values[key]
if (isFunction(code)) {
injectionCodes.push(`${importVar}.${key} = ${JSON.stringify(code(dep))}`)
} else {
injectionCodes.push(`${importVar}.${key} = ${toCode(code)}`)
}
})

let ret = injectionCodes.join('\n')
ret = ret.length > 0 ? `\n${ret}\n` : ''
return (ret += `/* harmony default export */ __webpack_exports__["default"] = (${importVar});`)
}

class VueComponentDependencyTemplate {
apply(dep: VueComponentDependency, source: ReplaceSource) {
const repleacements = source.replacements
const orgReplace = repleacements[repleacements.length - 1]
if (dep.statement.declaration.start !== orgReplace.start) {
return
}

const code = generateCode(dep, orgReplace.content)
// console.log('generateCode', code, dep.statement, orgReplace)
// source.insert(dep.statement.declaration.range[0], code)
source.replace(orgReplace.start, orgReplace.end, code)
}
}

VueComponentDependency.Template = VueComponentDependencyTemplate

function getScriptBlockModule(parser: any): NormalModule | undefined {
return parser.state.current.dependencies.find((dep: any) => {
const req = dep.userRequest || dep.request
if (req && dep.originModule) {
const query = parseQuery(req)
return query.type === 'script' && query.lang === 'js'
} else {
return false
}
})
}

function getTemplateBlockModule(parser: any): NormalModule | undefined {
return parser.state.current.dependencies.find((dep: any) => {
const req = dep.userRequest || dep.request
if (req && dep.originModule) {
const query = parseQuery(req)
return query.type === 'template'
} else {
return false
}
})
}

function toVueComponentDependency(parser: any, values: InjectionValues) {
return function vueComponentDependencyw(statement: any) {
// console.log('toVueComponentDependency##statement', statement)
const dep = new VueComponentDependency(
getScriptBlockModule(parser),
getTemplateBlockModule(parser),
values,
statement
)
// dep.loc = expr.loc
parser.state.current.addDependency(dep)
return true
}
}

export default class IntlifyVuePlugin implements webpack.Plugin {
injections: InjectionValues

constructor(injections: InjectionValues = {}) {
this.injections = injections
}

apply(compiler: webpack.Compiler): void {
const injections = this.injections

compiler.hooks.compilation.tap(
PLUGIN_ID,
(compilation, { normalModuleFactory }) => {
// compilation.dependencyFactories.set(
// // @ts-ignore
// VueComponentDependency,
// new NullFactory()
// )
compilation.dependencyTemplates.set(
// @ts-ignore
VueComponentDependency,
// @ts-ignore
new VueComponentDependency.Template()
)

normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(PLUGIN_ID, parser => {
parser.hooks.exportExpression.tap(
PLUGIN_ID,
(statement, declaration) => {
if (declaration.name === 'script') {
// console.log('exportExpression', statement, declaration)
return toVueComponentDependency(parser, injections)(statement)
}
}
)
})
}
)
}
}

/* eslint-enable @typescript-eslint/no-explicit-any */
8 changes: 8 additions & 0 deletions src/pluginWebpack5.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import webpack from 'webpack'

export default class IntlifyVuePlugin implements webpack.Plugin {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
apply(compiler: webpack.Compiler): void {
console.error('[@intlify/vue-i18n-loader] Cannot support webpack5 yet')
}
}
10 changes: 10 additions & 0 deletions test/fixtures/global.vue
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
<template>
<h1>Meta</h1>
</template>

<script>
export default {
name: 'Meta'
}
</script>

<i18n global>
{
"en": {
Expand Down
15 changes: 15 additions & 0 deletions test/fixtures/plugin/basic.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<template>
<h1>Meta</h1>
</template>

<script>
export default {
name: 'Meta'
}
</script>

<i18n>
{
"ja": "hello"
}
</i18n>
5 changes: 5 additions & 0 deletions test/fixtures/plugin/script.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
export default {
name: 'Meta'
}
</script>
35 changes: 35 additions & 0 deletions test/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { bundleAndRun, bundleEx } from './utils'

const options = {
a: 1,
b: 'hello',
c: {
a: 1,
nest: {
foo: 'hello'
}
},
d: () => 'hello'
}

test('basic', async () => {
const { module } = await bundleAndRun('./plugin/basic.vue', bundleEx, {
intlify: options
})
expect(module.a).toEqual(1)
expect(module.b).toEqual('hello')
expect(module.c.a).toEqual(1)
expect(module.c.nest.foo).toEqual('hello')
expect(module.d).toEqual('hello')
})

test('script only', async () => {
const { module } = await bundleAndRun('./plugin/script.vue', bundleEx, {
intlify: options
})
expect(module.a).toEqual(1)
expect(module.b).toEqual('hello')
expect(module.c.a).toEqual(1)
expect(module.c.nest.foo).toEqual('hello')
expect(module.d).toEqual('hello')
})
Loading