1. 程式人生 > >基於webpack搭建到抽離前端元件到釋出在npm庫

基於webpack搭建到抽離前端元件到釋出在npm庫

本篇分為三個部分,webpack搭建,前端元件抽離,在npm庫上釋出自己的包(基於vue)

webpack搭建

  1. 用npm init初始化,得到package.json,下載幾個常見的webpack中的包,配置“dev”,“build”用於執行和打包專案。
    執行專案的配置則存在於webpack.dev.config.js檔案中
    打包專案的配置存在於webpack.build.config.js檔案中
{
  "name": "@kuke/head-ui",
  "version": "1.0.0",
  "description": "表單框架頭部元件",
  "main": "index.js"
, "scripts": { "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --config build/webpack.dev.config.js", "build": "webpack --config build/webpack.build.config.js" }, "repository": { "type": "git", "url": "www" }, "devDependencies": { }, "dependencies"
: { "cross-env": "^3.0.0", //跨平臺的設定及使用環境變數,無需擔心跨平臺問題 "webpack": "^2.2.0", "webpack-dev-server": "^2.2.0" // 預設以當前目錄為基準目錄 }, "author": "rookie.he", "license": "ISC" }
  1. 配置webpack.build.config.js檔案和webpack.dev.config.js檔案(可直接複製使用)
    webpack.dev.config.js:
var path = require('path'
) // 用於規範化路徑 var webpack = require('webpack') module.exports = { entry: './example/main.js', // 入口檔案,即打包從哪個檔案開始 output: { // 生成的檔案輸出到哪個地方去 path: path.resolve(__dirname, './dist'), // 返回一個相對於當前工程目錄的絕對路徑 publicPath: '/dist/', filename: 'build.js' // 輸出的檔名稱 }, module: { rules: [ // 模組解析規則,下面是一些檔案及對應的loader { test: /\.vue$/, loader: 'vue-loader', options: { loaders: {} } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.less$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "less-loader", options: { paths: [ path.resolve(__dirname, "node_modules") ] } }] }, { test: /\.(svg|woff|ttf|eot|woff2)$/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]?[hash]' } } ] }, resolve: { // 影響模組的解析規則 alias: { // 用其它模組或路徑替換一個模組 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { // 指當webpack config傳給webpack-dev-server命令列時,這個選項用來配置webpack-dev-server的一些行為。 historyApiFallback: true, noInfo: true }, performance: { // 關閉提示 hints: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { // 當如下平臺環境時,進行下列操作 module.exports.devtool = '#source-map' module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }

webpack.build.config.js:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, '../dist'),
        publicPath: '/dist/',
        filename: 'kuke-ui.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {}
                    // other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.less$/,
                use: [{
                    loader: "style-loader"
                }, {
                    loader: "css-loader"
                }, {
                    loader: "less-loader", options: {
                        paths: [
                            path.resolve(__dirname, "node_modules")
                        ]
                    }
                }]
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue'
        }
    }
};

注意完成上述操作我們需要增加許多包:

"devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-preset-latest": "^6.0.0",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "less": "^2.7.2",
    "less-loader": "^4.0.3",
    "style-loader": "^0.16.1",
    "vue": "^2.2.1",
    "vue-loader": "^11.1.4",
    "vue-router": "^2.5.3",
    "vue-template-compiler": "^2.2.1",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.2.0"
  },

因為我們是在es2015環境下進行的操作,所以需要建立一個.babelrc檔案放在根目錄中

{
  "presets": [
    ["latest", {
      "es2015": { "modules": false }
    }]
  ]
}

因為上述打包的配置中的檔案暫不存在,所以我們需要見一些檔案,檔案目錄如下:
這裡寫圖片描述
此時執行npm run dev正常,執行npm run build正常,打包完成後會在根目錄下生成一個dist資料夾,裡面包含kuke-ui.js檔案

元件抽離

把抽離的元件放在src檔案下面,而example檔案下放一些元件的例項
1. 在src檔案下新建一個components檔案,components檔案下放一些抽離的元件,具體的元件內容可以到我的git倉庫下載,下面以SearchBar為例。
2. 在src中的index.js檔案中進行配置

import SearchBar from './components/SearchBar'

const kukeview = {
    'kuke-searchbar': SearchBar,
}

const install = function(Vue, opts = {}){
    Object.keys(kukeview).forEach((key) => {
        Vue.component(key, kukeview[key]);     // 遍歷,並註冊每一個元件
    })
}
export default install;
  1. 在example中引用元件,main.js中引入必要檔案
import Vue from 'vue'
import router from './router'
import App from './App.vue'
import kukeui from '../src/index'
import iView from 'iview'
import 'iview/dist/styles/iview.css'
import './fonts/iconfont.css'
// 引入axios
import axios from 'axios';
import VueAxios from 'vue-axios';
Vue.use(VueAxios, axios)
Vue.use(kukeui)
Vue.use(iView)

new Vue({
    router,
    el: '#app',
    render: h => h(App)
})
  1. 部署路由
import Vue from 'vue'
import Router from 'vue-router'
import SearchBar from '../pages/SearchBar.vue'

Vue.use(Router);

export default new Router({
    routes: [
        {
            path: '/SearchBar',
            name: 'SearchBar',
            component: SearchBar
        }
    ]
})

完成元件的抽離,效果示例效果如下:
這裡寫圖片描述