refactoring

This commit is contained in:
Philipp Kühn
2018-08-22 10:01:51 +02:00
parent 871f91ed27
commit 6a42cd4c0e
12 changed files with 50 additions and 157 deletions

24
build/examples/build.js Normal file
View File

@@ -0,0 +1,24 @@
import ora from 'ora'
import webpack from 'webpack'
import config from './webpack.config'
const spinner = ora('Building …')
export default new Promise((resolve, reject) => {
spinner.start()
webpack(config, (error, stats) => {
if (error) {
return reject(error)
}
if (stats.hasErrors()) {
process.stdout.write(stats.toString() + "\n");
return reject(new Error('Build failed with errors.'))
}
return resolve('Build complete.')
})
})
.then(success => spinner.succeed(success))
.catch(error => spinner.fail(error))

6
build/examples/paths.js Normal file
View File

@@ -0,0 +1,6 @@
import path from 'path'
export const rootPath = path.resolve(__dirname, '../')
export const srcPath = path.resolve(rootPath, '../examples')
export const buildPath = path.resolve(rootPath, '../docs')
export const sassImportPath = srcPath

51
build/examples/server.js Normal file
View File

@@ -0,0 +1,51 @@
import path from 'path'
import browserSync from 'browser-sync'
import webpack from 'webpack'
import httpProxyMiddleware from 'http-proxy-middleware'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from './webpack.config'
import { sassImport } from './utilities'
import { srcPath, sassImportPath } from './paths'
const bundler = webpack(config)
const middlewares = []
// add webpack stuff
middlewares.push(webpackDevMiddleware(bundler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false,
},
}))
// add hot reloading
middlewares.push(webpackHotMiddleware(bundler))
// start browsersync
const url = 'http://localhost'
const bs = browserSync.create()
const server = bs.init({
server: {
baseDir: `${srcPath}/`,
middleware: middlewares,
},
files: [],
logLevel: 'silent',
open: false,
notify: false,
injectChanges: false,
ghostMode: {
clicks: false,
forms: false,
scroll: false,
},
})
console.log(`${url}:${server.options.get('port')}`)
// sass import
bs.watch(path.join(sassImportPath, '**/!(index|index_sub).scss'), { ignoreInitial: true }, () => {
sassImport(sassImportPath)
})

View File

@@ -0,0 +1,47 @@
import fs from 'fs'
import path from 'path'
import glob from 'glob'
import minimist from 'minimist'
let argv = minimist(process.argv.slice(2))
export function removeEmpty(array) {
return array.filter(entry => !!entry)
}
export function ifElse(condition) {
return (then, otherwise) => (condition ? then : otherwise)
}
export const env = argv.env || 'development'
export const use = argv.use || null
export const isDev = use ? use === 'development' : env === 'development'
export const isProd = use ? use === 'production' : env === 'production'
export const isTest = env === 'testing'
export const ifDev = ifElse(isDev)
export const ifProd = ifElse(isProd)
export const ifTest = ifElse(isTest)
export function sassImport(basePath) {
const indexFileName = 'index.scss'
glob.sync(`${basePath}/**/${indexFileName}`).forEach(sourceFile => {
fs.writeFileSync(sourceFile, '// This is a dynamically generated file \n\n')
glob.sync(`${path.dirname(sourceFile)}/*.scss`).forEach(file => {
if (path.basename(file) !== indexFileName) {
fs.appendFileSync(sourceFile, `@import "${path.basename(file)}";\n`)
}
})
})
const indexSubFileName = 'index_sub.scss'
glob.sync(`${basePath}/**/${indexSubFileName}`).forEach(sourceFile => {
fs.writeFileSync(sourceFile, '// This is a dynamically generated file \n\n')
glob.sync(`${path.dirname(sourceFile)}/**/*.scss`).forEach(file => {
if (path.basename(file) !== indexSubFileName) {
let importPath = (path.dirname(sourceFile) === path.dirname(file)) ? path.basename(file) : file
importPath = importPath.replace(`${path.dirname(sourceFile)}/`, '')
fs.appendFileSync(sourceFile, `@import "${importPath}";\n`)
}
})
})
}

View File

@@ -0,0 +1,215 @@
import path from 'path'
import webpack from 'webpack'
import { VueLoaderPlugin } from 'vue-loader'
import SvgStore from 'webpack-svgstore-plugin'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ManifestPlugin from 'webpack-manifest-plugin'
import ImageminWebpackPlugin from 'imagemin-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin'
import { ifDev, ifProd, removeEmpty } from './utilities'
import { rootPath, srcPath, buildPath } from './paths'
export default {
mode: ifDev('development', 'production'),
entry: {
examples: removeEmpty([
ifDev('webpack-hot-middleware/client?reload=true'),
`${srcPath}/assets/sass/main.scss`,
`${srcPath}/main.js`,
]),
},
output: {
path: `${buildPath}/`,
filename: `assets/js/[name]${ifProd('.[hash]', '')}.js`,
chunkFilename: `assets/js/[name]${ifProd('.[chunkhash]', '')}.js`,
publicPath: '/',
},
resolve: {
extensions: ['.js', '.scss', '.vue'],
alias: {
vue$: 'vue/dist/vue.esm.js',
modernizr: path.resolve(rootPath, '../.modernizr'),
modules: path.resolve(rootPath, '../node_modules'),
images: `${srcPath}/assets/images`,
fonts: `${srcPath}/assets/fonts`,
variables: `${srcPath}/assets/sass/variables`,
settings: `${srcPath}/assets/sass/1-settings/index`,
utilityFunctions: `${srcPath}/assets/sass/2-utility-functions/index`,
tiptap: path.resolve(rootPath, '../src'),
},
modules: [
srcPath,
path.resolve(rootPath, '../node_modules'),
],
},
devtool: ifDev('eval-source-map', 'source-map'),
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.js$/,
loader: ifDev('babel-loader?cacheDirectory=true', 'babel-loader'),
exclude: /node_modules(?!\/quill)/,
},
{
test: /\.(graphql|gql)$/,
loader: 'graphql-tag/loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: removeEmpty([
ifDev('vue-style-loader', MiniCssExtractPlugin.loader),
'css-loader',
'postcss-loader',
]),
},
{
test: /\.scss$/,
use: removeEmpty([
ifDev('vue-style-loader', MiniCssExtractPlugin.loader),
'css-loader',
'postcss-loader',
'sass-loader',
]),
},
{
test: /\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: `assets/images/[name]${ifProd('.[hash]', '')}.[ext]`,
},
},
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: `assets/fonts/[name]${ifProd('.[hash]', '')}.[ext]`,
},
},
},
],
},
// splitting out the vendor
optimization: {
namedModules: true,
splitChunks: {
name: 'vendor',
minChunks: 2,
},
noEmitOnErrors: true,
// concatenateModules: true,
},
plugins: removeEmpty([
// create manifest file for server-side asset manipulation
new ManifestPlugin({
fileName: 'assets/manifest.json',
writeToFileEmit: true,
}),
// define env
// new webpack.DefinePlugin({
// 'process.env': {},
// }),
// copy static files
new CopyWebpackPlugin([
{
context: `${srcPath}/assets/static`,
from: { glob: '**/*', dot: false },
to: `${buildPath}/assets`,
},
]),
// enable hot reloading
ifDev(new webpack.HotModuleReplacementPlugin()),
// html
new HtmlWebpackPlugin({
filename: 'index.html',
template: `${srcPath}/index.html`,
inject: true,
minify: ifProd({
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
}),
buildVersion: new Date().valueOf(),
chunksSortMode: 'none',
}),
new VueLoaderPlugin(),
// create css files
ifProd(new MiniCssExtractPlugin({
filename: `assets/css/[name]${ifProd('.[hash]', '')}.css`,
chunkFilename: `assets/css/[name]${ifProd('.[hash]', '')}.css`,
})),
// minify css files
ifProd(new OptimizeCssAssetsPlugin({
cssProcessorOptions: {
reduceIdents: false,
autoprefixer: false,
zindex: false,
discardComments: {
removeAll: true,
},
},
})),
// svg icons
new SvgStore({
prefix: 'icon--',
svgoOptions: {
plugins: [
{ cleanupIDs: false },
{ collapseGroups: false },
{ removeTitle: true },
],
},
}),
// image optimization
new ImageminWebpackPlugin({
optipng: ifDev(null, {
optimizationLevel: 3,
}),
jpegtran: ifDev(null, {
progressive: true,
quality: 80,
}),
svgo: ifDev(null, {
plugins: [
{ cleanupIDs: false },
{ removeViewBox: false },
{ removeUselessStrokeAndFill: false },
{ removeEmptyAttrs: false },
],
}),
}),
]),
node: {
fs: 'empty',
},
}

165
build/package/_old.js Normal file
View File

@@ -0,0 +1,165 @@
const fs = require('fs')
const path = require('path')
const zlib = require('zlib')
const uglify = require('uglify-js')
const rollup = require('rollup')
// const configs = require('./configs')
const buble = require('rollup-plugin-buble')
const flow = require('rollup-plugin-flow-no-whitespace')
const cjs = require('rollup-plugin-commonjs')
const node = require('rollup-plugin-node-resolve')
const replace = require('rollup-plugin-replace')
const vue = require('rollup-plugin-vue')
const babel = require('rollup-plugin-babel')
// const resolveee = require('rollup-plugin-node-resolve')
// console.log('looool', VuePlugin)
const version = require('../package.json').version
const banner =
`/*!
* tiptap v${version}
* (c) ${new Date().getFullYear()} Philipp Kühn
* @license MIT
*/`
const resolve = _path => path.resolve(__dirname, '../', _path)
console.log(resolve('src/index.js'))
function genConfig(opts) {
const config = {
input: {
input: resolve('src/index.js'),
plugins: [
// resolveee({
// extensions: [ '.mjs', '.js', '.jsx', '.json' ],
// }),
// vue.default(),
// flow(),
// babel(),
node({
extensions: [ '.mjs', '.js', '.jsx', '.json' ],
}),
// cjs(),
// buble(),
],
},
output: {
file: opts.file,
format: opts.format,
banner,
name: 'tiptap',
},
external: [ 'vue', 'prosemirror-model' ]
}
if (opts.env) {
config.input.plugins.unshift(replace({
'process.env.NODE_ENV': JSON.stringify(opts.env)
}))
}
return config
}
if (!fs.existsSync('dist')) {
fs.mkdirSync('dist')
}
const configs = [
// browser dev
{
file: resolve('dist/tiptap.js'),
format: 'umd',
env: 'development'
},
// {
// file: resolve('dist/tiptap.min.js'),
// format: 'umd',
// env: 'production'
// },
// {
// file: resolve('dist/tiptap.common.js'),
// format: 'cjs'
// },
// {
// file: resolve('dist/tiptap.esm.js'),
// format: 'es'
// }
].map(genConfig)
function build (builds) {
let built = 0
const total = builds.length
const next = () => {
buildEntry(builds[built]).then(() => {
built++
if (built < total) {
next()
}
}).catch(logError)
}
next()
}
function buildEntry ({ input, output }) {
const isProd = /min\.js$/.test(output.file)
return rollup.rollup(input)
.then(bundle => bundle.generate(output))
.then(({ code }) => {
if (isProd) {
const minified = uglify.minify(code, {
output: {
preamble: output.banner,
/* eslint-disable camelcase */
ascii_only: true
/* eslint-enable camelcase */
}
}).code
return write(output.file, minified, true)
} else {
return write(output.file, code)
}
})
}
function write (dest, code, zip) {
return new Promise((resolve, reject) => {
function report (extra) {
console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''))
resolve()
}
fs.writeFile(dest, code, err => {
if (err) return reject(err)
if (zip) {
zlib.gzip(code, (err, zipped) => {
if (err) return reject(err)
report(' (gzipped: ' + getSize(zipped) + ')')
})
} else {
report()
}
})
})
}
function getSize (code) {
return (code.length / 1024).toFixed(2) + 'kb'
}
function logError (e) {
console.log(e)
}
function blue (str) {
return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
build(configs)

View File

@@ -0,0 +1,26 @@
import vue from 'rollup-plugin-vue'
import buble from 'rollup-plugin-buble'
import cjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
export default {
input: 'src/index.js',
output: {
name: 'tiptap',
exports: 'named',
format: 'cjs',
file: 'dist/tiptap.min.js',
},
sourcemap: true,
plugins: [
vue({
css: true,
compileTemplate: true,
}),
cjs(),
buble({
objectAssign: 'Object.assign',
}),
resolve(),
],
}