Skip to content

feat: intlify vue plugin for v1 #173

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

Merged
merged 1 commit into from
Mar 3, 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
8 changes: 5 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 @@ -29,6 +29,8 @@ module.exports = {
'object-curly-spacing': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-use-before-define': 'off'
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/ban-ts-comment': 'off'
}
}
49 changes: 25 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,46 +24,46 @@
}
},
"dependencies": {
"@intlify/shared": "^9.0.0",
"js-yaml": "^3.13.1",
"json5": "^2.1.1"
},
"devDependencies": {
"@types/jest": "^25.0.0",
"@types/jest": "^26.0.16",
"@types/js-yaml": "^3.12.1",
"@types/jsdom": "^16.0.0",
"@types/jsdom": "^16.2.5",
"@types/json5": "^0.0.30",
"@types/memory-fs": "^0.3.2",
"@types/node": "^13.1.4",
"@types/webpack": "^4.41.1",
"@types/node": "^14.14.10",
"@types/webpack": "^4.41.26",
"@types/webpack-merge": "^4.1.5",
"@typescript-eslint/eslint-plugin": "^2.26.0",
"@typescript-eslint/parser": "^2.26.0",
"@typescript-eslint/typescript-estree": "^2.26.0",
"@typescript-eslint/eslint-plugin": "^4.15.0",
"@typescript-eslint/parser": "^4.15.0",
"babel-loader": "^8.1.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.2",
"eslint": "^7.21.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue-libs": "^4.0.0",
"jest": "^25.2.4",
"jest": "^26.6.3",
"jest-puppeteer": "^4.4.0",
"jest-watch-typeahead": "^0.5.0",
"jsdom": "^16.0.0",
"lerna-changelog": "^1.0.0",
"jest-watch-typeahead": "^0.6.0",
"jsdom": "^16.4.0",
"lerna-changelog": "^1.0.1",
"memory-fs": "^0.5.0",
"opener": "^1.5.1",
"opener": "^1.5.2",
"prettier": "^2.0.4",
"puppeteer": "^2.1.1",
"shipjs": "^0.18.0",
"ts-jest": "^25.3.0",
"typescript": "^3.8.3",
"typescript-eslint-language-service": "^2.0.3",
"shipjs": "^0.23.0",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3",
"typescript-eslint-language-service": "^4.1.3",
"vue": "^2.6.11",
"vue-i18n": "^8.16.0",
"vue-loader": "^15.7.0",
"vue-i18n": "^8.23.0",
"vue-loader": "^15.9.6",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^4.2.2"
},
"engines": {
Expand Down Expand Up @@ -95,6 +95,7 @@
"lint:fix": "yarn lint --fix",
"release:prepare": "shipjs prepare",
"release:trigger": "shipjs trigger",
"fix": "yarn format:fix && yarn lint:fix",
"format": "prettier --config .prettierrc --ignore-path .prettierignore '**/*.{js,json,html}'",
"format:fix": "yarn format --write",
"test": "yarn lint && yarn test:cover && yarn test:e2e",
Expand Down
2 changes: 1 addition & 1 deletion ship.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async function commitChangelog(current, next) {
}

module.exports = {
mergeStrategy: { toSameBranch: ['master'] },
mergeStrategy: { toSameBranch: ['v1.x'] },
monorepo: undefined,
updateChangelog: false,
beforeCommitChanges: ({ nextVersion, exec, dir }) => {
Expand Down
34 changes: 34 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
;(async () => {
try {
await import('vue-i18n')
} catch (e) {
throw new Error(
'@intlify/vue-i18n-loader requires vue-i18n to be present in the dependency tree.'
)
}
})()

import webpack from 'webpack'

declare class IntlifyVuePlugin {
// 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 of your application.`
)
// console.log('[@intlify/vue-i18n-loader] webpack version:', webpack.version)

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
238 changes: 238 additions & 0 deletions src/pluginWebpack4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
/* 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 NullFactory = require('webpack/lib/NullFactory') // 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
template?: 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
}

get type() {
return 'harmony export expression'
}

getExports() {
return {
exports: ['default'],
dependencies: undefined
}
}

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.template
hash.update(
(templateModule &&
(!templateModule.buildMeta || templateModule.buildMeta.exportsType)) +
''
)
hash.update((templateModule && templateModule.id) + '')
}
}

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 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]
const code = generateCode(dep, 'component.exports')
// console.log('generateCode', code, dep.statement, orgReplace)
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 = statement.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()
)

const handler = (
parser: webpack.compilation.normalModuleFactory.Parser
) => {
parser.hooks.exportExpression.tap(
PLUGIN_ID,
(statement, declaration) => {
if (
(parser as any).state.module.resource.endsWith('.vue') &&
declaration.object.name === 'component' &&
declaration.property.name === 'exports'
) {
// console.log('exportExpression', statement, declaration)
return toVueComponentDependency(parser, injections)(statement)
}
}
)
}

normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(PLUGIN_ID, handler)
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(PLUGIN_ID, handler)
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(PLUGIN_ID, handler)
}
)
}
}

/* eslint-enable @typescript-eslint/no-explicit-any */
Loading