preface
At present, front-end packaging tools mainly include Webpack, rollup, gulp, etc.
Gulp is a task-based automated build tool.
Webpack is currently the most popular front-end resource modular management and packaging tool. It can package many loose modules according to dependencies and rules into front-end resources suitable for production deployment. You can also split up the code for modules that are loaded on demand and load them asynchronously when they are actually needed.
Rollup is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces of code, such as libraries or applications.
Rollup uses new standardized formats for code modules that are included in the ES6 version of JavaScript, rather than previous ad-hoc solutions such as CommonJS and AMD. ES6 modules allow you to use the most useful stand-alone functions in your favorite library freely and seamlessly, without having to carry around other unused code in your projects. ES6 modules will eventually be implemented natively in the browser, but the current Rollup gives you an early taste.
To put it simply, GulP is suitable for small projects and is process-based. Webpack is suitable for large application projects, divided into modules and loaded on demand; Rollup is good for building libraries and optimizing code. At present, front-end vUE and React frameworks are packaged with rollup, and some UI frameworks are also packaged with rollup.
This article ideas referenceElement3Vue3 + rollup + TS + gulp
Initialization work
Initialize a project with NPM init, and then install the necessary NPM packages:
/ / initialization
npm init
// Install the necessary rollup NPM packages
yarn add -D
rollup-plugin-vue // Similar to webpack vue-loader, vUE component loader
rollup-plugin-scss // SCSS parsing plug-in
rollup-plugin-peer-deps-external // Use package.json to exclude packages in the peerDependencies field
@rollup/plugin-node-resolve // Use Node parsing algorithm to locate modules
@rollup/plugin-commonjs // CommonJS module conversion
@rollup/plugin-json // json file parsing
@rollup/plugin-replace // Replace the string in the file when it is packaged
@rollup/plugin-babel // Translate new JavaScript features
rollup-plugin-typescript2 // Parse ts files and generate x.d.ts files
rollup-plugin-terser // Package minimization, i.e., compression
// Install @vue/ compiler-Sfc @babel/core typescript rollup
// package.json
{
"peerDependencies": { // Packaging will exclude vUE
"vue": "^ 3.0.11." "}}Copy the code
Create tsconfig.json in the root directory
{
"compilerOptions": {
"target": "esnext"."module": "esnext"."jsx": "preserve"."declaration": true."importHelpers": true."moduleResolution": "node"."skipLibCheck": true."esModuleInterop": true."allowSyntheticDefaultImports": true."sourceMap": true."baseUrl": "."."allowJs": true."lib": ["esnext"."dom"."dom.iterable"."scripthost"]."outDir": ". /"."resolveJsonModule": true
},
"include": ["src"."packages"]."exclude": ["node_modules"]}Copy the code
rollup.config.js
Then create rollup.config.js in the root directory
// Introduce rollup related packages
import pkg from './package.json'
import vuePlugin from 'rollup-plugin-vue'
import scss from 'rollup-plugin-scss'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import replace from '@rollup/plugin-replace'
import babel from '@rollup/plugin-babel'
import ts from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
// Define a base configuration
// Create header information for the package file
const createBanner = () = > {
return ` / *! *${pkg.name} v${pkg.version}
* (c) The ${new Date().getFullYear()} test
* @license ISC
*/`
}
// Create the base configuration
const createBaseConfig = () = > {
return {
input: 'src/index.ts'.// Load entry
external: ['vue'].plugins: [ // Plug-in loading
peerDepsExternal(),
vuePlugin({
css: true
}),
ts(),
babel({
exclude: 'node_modules/**'.extensions: ['.js'.'.jsx'.'.vue'].babelHelpers: 'bundled'
}),
resolve({
extensions: ['.vue'.'.jsx'.'.js']
}),
commonjs(),
json(),
scss()
],
output: {
sourcemap: false.banner: createBanner(),
externalLiveBindings: false.globals: {
vue: 'Vue'}}}}Copy the code
Then define different formats of output and other configurations:
// Generate the file name
function createFileName(formatName) {
return `dist/taxreview.${formatName}.js`
}
// es-bundle
const esBundleConfig = {
plugins: [
replace({
preventAssignment: true.__DEV__: `(process.env.NODE_ENV ! == 'production')`})].output: {
file: createFileName('esm-bundler'),
format: 'es'}}// cjs
const cjsConfig = {
plugins: [
replace({
preventAssignment: true.__DEV__: true})].output: {
file: createFileName('cjs'),
format: 'cjs'}}// cjs.prod
const cjsProdConfig = {
plugins: [
terser(),
replace({
preventAssignment: true.__DEV__: false})].output: {
file: createFileName('cjs.prod'),
format: 'cjs'}}// Other formats include es-browser global, etc
Copy the code
Pack different packages for different environments
/ / production
const prodFormatConfigs = [
esBundleConfig,
cjsConfig,
cjsProdConfig
]
const devFormatConfigs = [esBundleConfig] / / development
Copy the code
Finally, the package is executed
function mergeConfig(baseConfig, configB) {
const config = Object.assign({}, baseConfig)
// plugin
if(configB.plugins) { baseConfig.plugins.push(... configB.plugins) }// output
config.output = Object.assign({}, baseConfig.output, configB.output)
return config
}
function createPackageConfigs() {
return getFormatConfigs().map((formatConfig) = > {
return mergeConfig(createBaseConfig(), formatConfig)
})
}
function getFormatConfigs() {
return process.env.NODE_ENV === 'development'
? devFormatConfigs
: prodFormatConfigs
}
export default createPackageConfigs()
Copy the code
Processing of VUE components
Create a new packages folder in the root directory for all components and a new theme-Chalk folder in the packages directory for SCSS files. Do not write SCSS directly in the vue file. After that, SCSS files in theme-Chalk are packaged with gulP.
// packages/Test/src/Test.vue
<template>
<div>
{{msg}}
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'test'.setup() {
let msg = ref('test')
return { msg }
}
})
</script>
Copy the code
// packages/Test/index.ts
import Test from './src/Test.vue'
/* istanbul ignore next */
Test.install = function (app) {
app.component(Test.name, Test)
}
export { Test }
Copy the code
Then start the entire program in the root directory SRC /index.ts
// src/index.ts
import { Test } from '.. /packages/Test'
import { version } from '.. /package.json'
import { setupGlobalOptions } from './globalConfig' // This file is used to set some global properties of the UI library
const components = [
Test
]
Vue. Use is used to register global components
const install = (app, opts = {}) = > {
app.use(setupGlobalOptions(opts))
components.forEach((component) = > {
app.use(component)
})
applyOptions(app)
}
// This is used to mount components called with JS such as Message
function applyOptions(app) {
app.config.globalProperties.$test = Test
}
const taxreview = {
version,
install
}
// This is for a separate reference
export {
Test,
install
}
export default taxreview
Copy the code
// SRC/globalconfig. ts is used to set some global properties of the UI library
import { getCurrentInstance } from 'vue'
/** * get globalOptions $TAXREVIEW config object */
export function useGlobalOptions() {
const instance = getCurrentInstance()
if(! instance) {console.warn('useGlobalOptions must be call in setup function')
return
}
return instance.appContext.config.globalProperties.$TAXREVIEW || {}
}
export function setupGlobalOptions(opts: any = {}) {
return (app) = > {
app.config.globalProperties.$TAXREVIEW = {
size: opts.size || ' '.zIndex: opts.zIndex || 2000}}}Copy the code
We also need to modify package.json
{
"main": "dist/taxreview.cjs.js".// Import the main entry file of the package
"types": "dist/src/index.d.ts".// Specify the type declaration file
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."build": "rollup -c" // Start packing
}
// Other configurations
}
Copy the code
From here, you can package vUE components with YARN Build
CSS
All of our CSS is placed under Packages/Theme-chalk/SRC, so we can build gulp packaging in Packages /theme-chalk
// packages/theme-chalk/gulpfile.js
'use strict'
const { series, src, dest } = require('gulp')
const sass = require('gulp-sass')
const autoprefixer = require('gulp-autoprefixer')
const cssmin = require('gulp-cssmin')
// Convert SCSS files into CSS files and compress them into the same lib folder
function compile() {
return src('./src/*.scss')
.pipe(sass.sync())
.pipe(
autoprefixer({
overrideBrowserslist: ['ie > 9'.'last 2 versions'].cascade: false
})
)
.pipe(cssmin())
.pipe(dest('./lib'))}// Use to copy font files
function copyfont() {
return src('./src/fonts/**').pipe(cssmin()).pipe(dest('./lib/fonts'))}exports.build = series(compile, copyfont)
Copy the code
Then add another command to handle SCSS in the root package.json
// cp-cli A B: The command is to copy all files in path A to path B
{
"build:theme": "node scripts/generateCssFile.js && gulp build --gulpfile packages/theme-chalk/gulpfile.js && cp-cli packages/theme-chalk/lib lib/theme-chalk"
}
// yarn build:theme
Copy the code
The last
Finally we will package NPM publish to NPM, and then we can apply yarn Add XXX to the project.
Making: github.com/554246839/r… The master branch