UNPKG

2.67 kBJavaScriptView Raw
1const resolveFrom = require('resolve-from')
2const logger = require('@poi/cli-utils/logger')
3const loadConfig = require('./utils/load-config')
4
5module.exports = class Plugin {
6 /**
7 * Creates an instance of Plugin.
8 * @param {*} poi Root API
9 * @param {string} name Plugin name
10 */
11 constructor(poi, name) {
12 this._name = name
13 this.root = poi
14
15 poi._commands = poi._commands || new Map()
16
17 // Exposed
18 this.commands = poi._commands
19 this.hooks = poi.hooks
20 this.pkg = poi.pkg
21 this.config = poi.config
22 this.options = poi.options
23 this.loadConfig = loadConfig
24 this.logger = logger
25 }
26
27 get plugins() {
28 return this.root.plugins
29 }
30
31 get internals() {
32 return this.root.internals
33 }
34
35 get mode() {
36 return this.root.internals.mode
37 }
38
39 get command() {
40 return this.root.options.command
41 }
42
43 hook(...args) {
44 return this.root.hook(...args)
45 }
46
47 registerCommand(command, desc, handler) {
48 if (this.commands.has(command)) {
49 logger.debug(
50 `Plugin "${
51 this._name
52 }" overrided the command "${command}" that was previously added by plugin "${this.commands.get(
53 command
54 )}"`
55 )
56 }
57 this.commands.set(command, this._name)
58 return this.root.cli.command(command, desc, handler)
59 }
60
61 hasPlugin(name) {
62 return (
63 this.root.plugins &&
64 this.root.plugins.find(plugin => plugin.resolve.name === name)
65 )
66 }
67
68 removePlugin(name) {
69 this.root.plugins = this.root.plugins.filter(
70 plugin => plugin.resolve.name !== name
71 )
72 return this
73 }
74
75 resolveWebpackConfig(opts) {
76 return this.root.resolveWebpackConfig(opts)
77 }
78
79 createWebpackCompiler(webpackConfig) {
80 return this.root.createWebpackCompiler(webpackConfig)
81 }
82
83 runWebpack(webpackConfig) {
84 return this.root.runWebpack(webpackConfig)
85 }
86
87 resolve(...args) {
88 return this.root.resolve(...args)
89 }
90
91 chainWebpack(fn) {
92 this.hooks.add('chainWebpack', fn)
93 return this
94 }
95
96 configureDevServer(fn) {
97 this.hooks.add('configureDevServer', fn)
98 return this
99 }
100
101 bundle() {
102 return this.root.bundle()
103 }
104
105 setAppEnvs(envs) {
106 return this.root.setAppEnvs(envs)
107 }
108
109 getEnvs() {
110 return this.root.getEnvs()
111 }
112
113 localResolve(id, fallbackDir) {
114 let resolved = resolveFrom.silent(this.resolve(), id)
115 if (!resolved && fallbackDir) {
116 resolved = resolveFrom.silent(fallbackDir, id)
117 }
118 return resolved
119 }
120
121 localRequire(...args) {
122 const resolved = this.localResolve(...args)
123 return resolved && require(resolved)
124 }
125
126 hasDependency(...args) {
127 return this.root.hasDependency(...args)
128 }
129}