Skip to content

Commit e6375d9

Browse files
author
Shawn Wang
committed
update build tools
1 parent 6782263 commit e6375d9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+4108
-3817
lines changed

README.md

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
## 文件结构
2+
23
```
34
|——dist # 编译后的待发布目录
45
|——public # 公共资源目录
@@ -7,28 +8,32 @@
78
|--└——assets # 项目所需资源文件,如:图片、样式、字体
89
|--└——components # 公用的UI组件
910
|--└——environments # 项目的全局配置目录
10-
|--└——lib # 三方库目录
11+
|--└——└——.env.dev # development配置文件
12+
|--└——└——.env.prod # production配置文件
1113
|--└——routes # 路由配置及页面对应的 VUE 文件
1214
|--└——store # vuex 数据目录
1315
|--└——utils # 通用 utils 目录
1416
|--└——App.vue # 项目入口 VUE 文件
15-
|--└——global-components.vue # 全局组件模块
1617
|--└——main.ts # 项目入口 typescript 文件
1718
|--└——shims.d.ts # 类型、模块声明文件
19+
|——test # 测试文件目录
20+
|——.browserslistrc # browsers 配置文件
1821
|——.gitignore # gitignore 配置文件
22+
|——.prettierrc # prettier 配置文件
23+
|——babel.config.js # babel 配置文件
24+
|——dll.config.js # dll 配置文件
1925
|——package.json # npm 配置文件
26+
|——postcss.config.js # postcss 配置文件
2027
|——tsconfig.json # typescript 配置文件
21-
|——vue.config.js # vue cli 配置文件
28+
|——tslint.json # tslint 配置文件
2229
|——yarn.lock # yarn 依赖包信息文件
2330
```
2431

2532
## 运行步骤
33+
2634
1. yarn
2735
2. yarn run serve
2836

2937
## 构建步骤
30-
1. yarn run build
3138

32-
## 基于该模板的个人作品
33-
- [Todo List](https://www.shawnwang.ltd/#/todo-list/index?username=%E6%B5%8B%E8%AF%95%E4%B8%93%E7%94%A8)
34-
- [诗词大全](https://www.shawnwang.ltd/#/index/index)
39+
1. yarn run build

build/consts.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const path = require('path')
2+
const projectPath = process.cwd()
3+
const packageJSONPath = path.join(projectPath, 'package.json')
4+
const packageJSON = require(packageJSONPath)
5+
const webpackConfigPath = path.join(projectPath, 'build/webpack.config.js')
6+
const dllConfigPath = path.join(projectPath, 'dll.config.js')
7+
const dllConfig = require(dllConfigPath)
8+
const isProduction = process.env.NODE_ENV === 'production'
9+
const isServe = !!process.env.IS_SERVE
10+
const isAnalyze = !!process.env.IS_ANALYZE
11+
const envFilename = isProduction ? '.env.prod' : '.env.dev'
12+
const envFilePath = path.join(projectPath, `src/environments/${envFilename}`)
13+
14+
module.exports = {
15+
projectPath,
16+
packageJSONPath,
17+
packageJSON,
18+
webpackConfigPath,
19+
dllConfigPath,
20+
dllConfig,
21+
dllPath: 'public/vendor',
22+
envFilePath,
23+
isProduction,
24+
isServe,
25+
isAnalyze,
26+
}

build/run/dev-server.js

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,34 @@
1-
const { exec } = require('child_process')
2-
const chalk = require('chalk')
3-
const path = require('path')
4-
const projectPath = process.cwd()
1+
#!/usr/bin/env node
2+
3+
const spawn = require('cross-spawn')
54
let port = process.env.port || 9000
6-
const webpackDevServerPath = path.join(projectPath, 'node_modules/.bin/webpack-dev-server')
7-
const webpackConfigPath = path.join(projectPath, 'build/webpack.config.js')
5+
const { webpackConfigPath } = require('../consts')
86

97
function run() {
10-
const buildCommand = `${webpackDevServerPath} --config ${webpackConfigPath} --color --progress`
11-
console.log(chalk.blue(buildCommand))
12-
const child = exec(buildCommand, {
13-
maxBuffer: 2 * 1024 * 1024,
14-
env: {
15-
port,
16-
},
17-
}, (error, stdout, stderr) => {
18-
if (error) {
19-
if (error.message.includes('address already in use')) {
20-
console.clear()
21-
port++
22-
run()
23-
return
24-
}
25-
console.error(error.message)
8+
const command = `npx webpack-dev-server --config ${webpackConfigPath} --color`
9+
let file = '/bin/sh'
10+
let args = ['-c', command]
11+
if (process.platform === 'win32') {
12+
file = process.env.comspec || 'cmd.exe'
13+
args = ['/s', '/c', command]
14+
}
15+
16+
const child = spawn(file, args, {
17+
stdio: ['inherit', 'inherit', 'pipe'],
18+
env: { ...process.env, IS_SERVE: 'true', port },
19+
})
20+
child.stderr.on('data', errMsg => {
21+
console.error(`stderr: ${errMsg}`)
22+
if (errMsg.includes('address already in use')) {
23+
console.clear()
24+
port++
25+
run()
26+
return
2627
}
2728
})
28-
child.stdout.pipe(process.stdout)
29+
child.on('close', code => {
30+
console.log(`closed, code: ${code}`)
31+
})
2932
}
3033

3134
run()

build/run/production.js

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,41 @@
1-
const { exec } = require('child_process')
2-
const path = require('path')
1+
const webpack = require('webpack')
32
const chalk = require('chalk')
4-
const projectPath = process.cwd()
5-
const webpackPath = path.join(projectPath, 'node_modules/.bin/webpack')
6-
const webpackConfigPath = path.join(projectPath, 'build/webpack.config.js')
3+
const ora = require('ora')
4+
const { webpackConfigPath } = require('../consts')
5+
const webpackConfig = require(webpackConfigPath)
6+
7+
const spinner = ora(`Building for ${process.env.NODE_ENV}...`)
8+
spinner.start()
79

810
function run() {
9-
const buildCommand = `${webpackPath} --config ${webpackConfigPath} --progress`
10-
console.log(chalk.blue(buildCommand))
11-
const child = exec(
12-
buildCommand,
13-
{
14-
maxBuffer: 2 * 1024 * 1024,
15-
},
16-
(error, stdout, stderr) => {
17-
if (error) {
18-
console.error(error.message)
11+
const compiler = webpack(webpackConfig)
12+
compiler.run((err, stats) => {
13+
spinner.stop()
14+
if (err) {
15+
console.error(err.stack || err)
16+
if (err.details) {
17+
console.error(err.details)
1918
}
19+
return
2020
}
21-
)
22-
23-
child.stdout.pipe(process.stdout)
21+
const info = stats.toJson()
22+
if (stats.hasErrors()) {
23+
console.error(info.errors)
24+
}
25+
if (stats.hasWarnings()) {
26+
console.warn(info.warnings)
27+
}
28+
process.stdout.write(
29+
stats.toString({
30+
colors: true,
31+
modules: false,
32+
children: false,
33+
chunks: false,
34+
chunkModules: false,
35+
}) + '\n'
36+
)
37+
console.log(chalk.cyan('Build complete.\n'))
38+
})
2439
}
2540

2641
run()

build/webpack-config/dev-server.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const path = require('path')
2-
const projectPath = process.cwd()
3-
const { devServerConfig } = require(path.join(projectPath, 'package.json'))
2+
const { projectPath, packageJSON } = require('../consts')
3+
4+
const { devServerConfig } = packageJSON
45

56
module.exports = {
67
watchContentBase: true,
@@ -21,12 +22,10 @@ module.exports = {
2122
historyApiFallback: {
2223
rewrites: [
2324
{ from: /^\/$/, to: '/index.html' },
24-
{ from: /./, to: '/index.html' }
25-
]
26-
},
27-
before: function (app, server) {
28-
},
29-
after(app, server) {
25+
{ from: /./, to: '/index.html' },
26+
],
3027
},
31-
allowedHosts: []
28+
before: function(app, server) {},
29+
after(app, server) {},
30+
allowedHosts: [],
3231
}

build/webpack-config/module.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
1-
const path = require('path')
21
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
3-
const isProduction = process.env.NODE_ENV === 'production'
4-
const projectPath = process.cwd()
5-
const { webpackConfig } = require(path.join(projectPath, 'package.json'))
2+
const { packageJSON, isProduction } = require('../consts')
63

74
module.exports = {
85
rules: [
@@ -42,7 +39,8 @@ module.exports = {
4239
},
4340
{
4441
test: /\.js$/,
45-
exclude: (resourcePath) => {
42+
exclude: resourcePath => {
43+
const webpackConfig = packageJSON.webpackConfig || {}
4644
const transplieRegArray = [...webpackConfig.transpileModules]
4745
if (/\Wnode_modules\W/.test(resourcePath)) {
4846
for (

build/webpack-config/optimization.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ module.exports = {
88
assetNameRegExp: /\.css$/g,
99
cssProcessor: require('cssnano'),
1010
cssProcessorPluginOptions: {
11-
preset: [ 'default', { discardComments: { removeAll: true } } ],
11+
preset: ['default', { discardComments: { removeAll: true } }],
1212
},
13-
canPrint: true
13+
canPrint: true,
1414
}),
1515
new TerserPlugin({
1616
test: /\.js$/i,
17-
exclude: /^vendor/,
1817
parallel: os.cpus().length,
1918
sourceMap: true,
2019
extractComments: false,
@@ -37,10 +36,10 @@ module.exports = {
3736
],
3837
splitChunks: {
3938
chunks: 'all',
40-
maxSize: 600 * 1024,
41-
minSize: 400 * 1024,
39+
maxSize: 244 * 1024,
40+
minSize: 200 * 1024,
4241
minChunks: 1,
4342
automaticNameDelimiter: '.',
44-
name: 'vendors',
43+
name: true,
4544
},
4645
}

build/webpack-config/plugins.js

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const path = require('path')
22
const os = require('os')
3+
const fs = require('fs')
34
const webpack = require('webpack')
45
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
56
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
@@ -8,22 +9,17 @@ const HtmlWebpackPlugin = require('html-webpack-plugin')
89
const VueLoaderPlugin = require('vue-loader/lib/plugin')
910
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
1011
const CopyWebpackPlugin = require('copy-webpack-plugin')
11-
const isProduction = process.env.NODE_ENV === 'production'
12-
const projectPath = process.cwd()
12+
const { projectPath, envFilePath, isServe, isAnalyze } = require('../consts')
1313

1414
const plugins = [
15-
new CleanWebpackPlugin({
16-
verbose: true,
17-
cleanStaleWebpackAssets: false,
18-
cleanOnceBeforeBuildPatterns: ['**/*'],
19-
}),
2015
new FriendlyErrorsWebpackPlugin({
2116
compilationSuccessInfo: {
2217
messages: compileMessages(),
2318
notes: [],
2419
},
2520
clearConsole: true,
2621
}),
22+
new webpack.DefinePlugin(getDefinePluginObj()),
2723
new webpack.DllReferencePlugin({
2824
context: projectPath,
2925
manifest: require(path.join(
@@ -32,10 +28,11 @@ const plugins = [
3228
)),
3329
}),
3430
new webpack.IgnorePlugin({
35-
checkResource: (resourcePath) => {
31+
checkResource: resourcePath => {
3632
if (/moment\/locale\/(?!zh-cn)/.test(resourcePath)) {
3733
return true
3834
}
35+
return false
3936
},
4037
}),
4138
new VueLoaderPlugin(),
@@ -59,16 +56,47 @@ const plugins = [
5956
]),
6057
]
6158

62-
if (process.env.isAnalyze) {
59+
if (!isServe) {
60+
plugins.unshift(
61+
new CleanWebpackPlugin({
62+
verbose: true,
63+
cleanStaleWebpackAssets: false,
64+
cleanOnceBeforeBuildPatterns: ['**/*'],
65+
})
66+
)
67+
}
68+
69+
if (isAnalyze) {
6370
plugins.push(new BundleAnalyzerPlugin())
6471
}
6572

73+
function getDefinePluginObj() {
74+
const obj = {}
75+
for (let p of Object.keys(process.env)) {
76+
if (p.startsWith('VUE_')) {
77+
obj[p] = process.env[p]
78+
}
79+
}
80+
if (fs.existsSync(envFilePath) && fs.statSync(envFilePath).isFile()) {
81+
const fileContent = fs.readFileSync(envFilePath).toString()
82+
const array = fileContent.split(/[\r\n]/)
83+
for (let i = 0, len = array.length; i < len; i++) {
84+
if (array[i].startsWith('#')) {
85+
continue
86+
}
87+
const itemArray = array[i].split('=')
88+
obj[itemArray[0]] = `'${itemArray[1]}'`
89+
}
90+
}
91+
return obj
92+
}
93+
6694
function getAccessUrlArray() {
6795
const result = []
6896
const netInterfaces = Object.entries(os.networkInterfaces())
6997
for (let netInterface of netInterfaces) {
7098
const interfaceInfo = netInterface[1]
71-
interfaceInfo.forEach((ipObj) => {
99+
interfaceInfo.forEach(ipObj => {
72100
if (ipObj.family === 'IPv4') {
73101
result.push(
74102
` - Access URL: http://${ipObj.address}:${process.env.port}/index.html`
@@ -81,7 +109,7 @@ function getAccessUrlArray() {
81109

82110
function compileMessages() {
83111
const messages = []
84-
if (!isProduction) {
112+
if (isServe) {
85113
return getAccessUrlArray().concat(messages)
86114
}
87115
return messages

0 commit comments

Comments
 (0)