Skip to content

Commit

Permalink
feat: 优化打包,以减少包的大小
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaofan9 committed Jul 20, 2021
1 parent 0023c2c commit 56c08c2
Show file tree
Hide file tree
Showing 15 changed files with 2,040 additions and 2,295 deletions.
3 changes: 1 addition & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ module.exports = {
},
'extends': [
'plugin:vue/essential',
'eslint:recommended',
'@vue/typescript/recommended'
'eslint:recommended'
],
parserOptions: {
ecmaVersion: 2020
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ jobs:
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm run build && npx gulp
- run: npm publish --tag beta
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
13 changes: 6 additions & 7 deletions Gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,20 @@
const { src, dest, series } = require('gulp');
const jsonEditor = require("gulp-json-editor");
const { Reflect } = require('core-js');
const { merge } = require('lodash');
const { cloneDeep } = require('lodash');

const foldPath = './';

function package() {
return src("package.json")
.pipe(jsonEditor(function(json) {
const existJson = {
scripts: {
test: 'echo "Error: no test specified" && exit 1'
}
};
const tmpJson = merge(json, existJson);
const tmpJson = cloneDeep(json);
Reflect.deleteProperty(tmpJson, 'devDependencies');

tmpJson.scripts = {
test: 'echo "Error: no test specified" && exit 1'
}

return tmpJson;
})).pipe(dest(foldPath));
}
Expand Down
44 changes: 44 additions & 0 deletions build/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const path = require('path');
const { genTranspileDepRegex } = require("./util");

exports.foldPath = path.resolve(__dirname, `..`);
exports.input = path.resolve(exports.foldPath, "src/index.js");

exports.output = {
path: path.resolve(exports.foldPath, './dist')
}

// 别名
exports.alias = {};

exports.vue = {
root: 'Vue',
commonjs: 'vue',
commonjs2: 'vue',
amd: 'vue'
};

exports.jsexclude = function (filepath){
const transpileDependencies = [];
const transpileDepRegex = genTranspileDepRegex(transpileDependencies);

// always transpile js in vue files
if (/\.vue\.jsx?$/.test(filepath)) {
return false
}

// only include @babel/runtime when the @vue/babel-preset-app preset is used
if (
process.env.VUE_CLI_TRANSPILE_BABEL_RUNTIME &&
filepath.includes(path.join('@babel', 'runtime'))
) {
return false
}

// check if this is something the user explicitly wants to transpile
if (transpileDepRegex && transpileDepRegex.test(filepath)) {
return false
}
// Don't transpile node_modules
return /node_modules/.test(filepath)
}
28 changes: 13 additions & 15 deletions build/build.js → build/rollup.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,31 @@ const cjs = require("@rollup/plugin-commonjs");
const pkg = require("../package.json");
const { DEFAULT_EXTENSIONS } = require("@babel/core");
const replace = require("@rollup/plugin-replace");
const config = require("./config");

const deps = ["vue", ...Object.keys(Object.assign({}, pkg.dependencies))];
const foldPath = path.resolve(__dirname, `..`);
const input = path.resolve(foldPath, "src/index.js");
const input = config.input;
const outputConfig = {
esm: {
format: "esm",
file: path.resolve(foldPath, `dist/${pkg.name}.esm.js`)
},
umd: {
file: path.resolve(config.output.path, `${pkg.name}.esm.js`)
}
};
const arguments = process.argv.splice(2);
const isDebug = arguments.includes('debug');
const commonExtensions = [".ts", ".tsx", ".vue"];

if(isDebug) {
outputConfig.umd = {
format: "umd",
file: path.resolve(foldPath, `dist/${pkg.name}.min.js`),
file: path.resolve(config.output.path, `${pkg.name}.min.js`),
name: "CountTo",
globals: {
vue: "Vue"
},
exports: "named"
}
};
const arguments = process.argv.splice(2);
const isDebug = arguments.includes('debug');
const commonExtensions = [".ts", ".tsx", ".vue"];
}

const runBuild = async () => {
const outputKeyList = Object.keys(outputConfig);
Expand Down Expand Up @@ -92,11 +95,6 @@ const runBuild = async () => {
}),
json(),
vue(),
// cjs({
// // 开启混合模式转换
// transformMixedEsModules: true,
// sourceMap: true
// }),
...extPlugins,
babel({
babelHelpers: "runtime",
Expand Down
19 changes: 19 additions & 0 deletions build/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const path = require("path");

exports.isWindows = process.platform === 'win32';

function genTranspileDepRegex (transpileDependencies) {
const deps = transpileDependencies.map(dep => {
if (typeof dep === 'string') {
const depPath = path.join('node_modules', dep, '/')
return exports.isWindows
? depPath.replace(/\\/g, '\\\\') // double escape for windows style path
: depPath
} else if (dep instanceof RegExp) {
return dep.source
}
})
return deps.length ? new RegExp(deps.join('|')) : null
}

exports.genTranspileDepRegex = genTranspileDepRegex;
67 changes: 67 additions & 0 deletions build/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const TerserPlugin = require('terser-webpack-plugin');
const config = require('./config');
const pkg = require('../package.json');

const arguments = process.argv.splice(2);
const isDebug = arguments.includes('debug');

module.exports = {
mode: 'production',
entry: {
[pkg.name]: config.input
},
output: {
filename: '[name].min.js',
chunkFilename: '[id].js',
libraryTarget: 'umd',
globalObject: 'typeof self !== \'undefined\' ? self : this',
...config.output
},
devtool: 'source-map',
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: config.alias
},
externals: {
vue: config.vue
},
optimization: isDebug ? {
minimize: false,
} : {
minimizer: [
new TerserPlugin({
extractComments: false,
}),
],
},
performance: {
hints: false
},
stats: {
children: false
},
module: {
rules: [
{
test: /\.(jsx?|babel|es6)$/,
include: process.cwd(),
exclude: config.jsexclude,
loader: 'babel-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
}
}
},
]
},
plugins: [
new VueLoaderPlugin()
]
};
79 changes: 79 additions & 0 deletions build/webpack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"use strict";

const ora = require("ora");
const rm = require("rimraf");
const path = require("path");
const chalk = require("chalk");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const merge = require("webpack-merge");
const config = require("./config");

let isModern = false;
let isOnly = false;

process.argv.forEach(item => {
if (item.includes("modern")) {
isModern = true;
}

if (item.includes("only")) {
isOnly = true;
}
});

let spinner;

function logStart(str = "") {
spinner = ora(`Building ${str}bundle for production...`);

spinner.start();
}

function build(webpackConfig, str) {
return new Promise(function (resolve, reject) {
logStart(str);

webpack(webpackConfig, function (err, stats) {
spinner.stop();
if (err) {
process.exit(1);

throw err;
}

if (stats.hasErrors()) {
console.log(stats.toString({
colors: true
}));

console.log(chalk.red("\nBuild failed with errors.\n"));

process.exit(1);
}

resolve();
});
});
}

(async function () {
rm(
config.output.path,
async err => {
if (err) {
spinner.stop();

process.exit(1);
throw err;
}
let startTime = Date.now();

await build(webpackConfig);

console.log(
chalk.green("Build complete in " + (Date.now() - startTime) + "ms.\n")
);
}
);
})();
2 changes: 0 additions & 2 deletions dist/vue3-count-to.esm.js

This file was deleted.

1 change: 0 additions & 1 deletion dist/vue3-count-to.esm.js.map

This file was deleted.

4 changes: 2 additions & 2 deletions dist/vue3-count-to.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/vue3-count-to.min.js.map

Large diffs are not rendered by default.

Loading

0 comments on commit 56c08c2

Please sign in to comment.