新建
vue
项目的过程见:https://blog.csdn.net/qq_37248504/article/details/107169812
build
下config
在vue/config/index.js
文件下配置vue/config/index.js
文件下的将build
对象下的assetsPublicPath
中的/
,改为./
npm run build
命令打包dist
文件夹下面生成打包的文件dist
文件夹下面会生成css、js、主页面(index.html)
文件index.html
,在路径的最后面加上路由地址可以访问对应的页面app.js
:app.js
就是app.vue
或者其它类似vue
文件的js
业务代码
webpack
打包后会在build
过程中产生Runtime
的部分(运行时的一部分代码)会被添加进入vendor.js
中
Webpack
是当下最热门的前端资源模块化管理和打包工具。它可以将许多松散的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分隔,等到实际需要的时候再异步加载。通过 loader
的转换,任何形式的资源都可以视作模块,比如 CommonJs
模块、 AMD
模块、 ES6
模块、CSS
、图片、 JSON
、Coffeescript
、 LESS
等。node.js
npm install --save-dev webpack
npm install --save-dev webpack@<version>
npm install --global webpack
npm
安装较慢,可以切换为cnpm
安装创建示例代码
详见:起步 | webpack 中文网 (webpackjs.com)
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
CLI
这种方式来运行本地的 webpack
不是特别方便,我们可以设置一个快捷方式。在 package.json
*添加一个 npm 脚本(npm script):"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build":"webpack"
},
npm run build
命令,来替代我们之前使用的 npx
命令。webpack
最出色的功能之一就是,除了 JavaScript
,还可以通过 loader
引入任何其他类型的文件。也就是说,以上列出的那些 JavaScript
的优点(例如显式依赖),同样可以用来构建网站或 web
应用程序中的所有非 JavaScript
内容。import
一个 CSS 文件,你需要在 module
配置中安装并添加 style-loader
和 css-loader
npm install --save-dev style-loader css-loader
JavaScript
提供了 source map
功能,将编译后的代码映射回原始源代码。如果一个错误来自于 b.js
,source map
就会明确的告诉你。
vue-demo
和模块vue-demo-two
,模块vue-demo
依赖模块vue-demo-two
,如果vue-demo-two
包已经发布到npm
仓库中了,那么直接npm install vue-demo-two
如果还没有发布使用本地的模块,那么使用 npm install
vue-demo-two
的绝对路径,依赖成功之后修改vue-demo-two
中main
后面的地址,这个地址是vue-demo-two
的入口地址。vue-demo
依赖本地的vue-demo-two
之后package.json
如下:"vue-demo-two": "file:../vue-demo-two",
vue-demo-two
中pacakge.json main
的信息如下:testone.js
是下面示例中的js
"main": "src/utils/testone.js",
vue-demo-two
封装的工具类/src/utils/testone.js
const log = function log (sth) {
return sth
}
const strOne = '张三'
const strTwo = '李四'
export default{
log,
strOne,
strTwo
}
export function one () {
console.log('one')
}
export function two () {
console.log('two')
}
npm install
vue-demo-two
的本地地址之后,修改vue-demo-two
中main
后面的地址"main": "src/utils/testone.js",
main
属性的话我们可能需要这样写引用:require("some-module/dist/app.js")
,如果我们在main
属性中指定了dist/app.js
的话,我们就可以直接引用依赖就可以了:require("some-module")
TestInput.vue
<template>
<div>
<el-input placeholder="我是测试组件" v-model="inputvalue" >el-input>
div>
template>
<script>
export default{
name: 'TestInput',
props: {
test: String
},
data: function () {
return {
inputvalue: '123'
}
},
computed: {
}
}
script>
lib.js
// 导出所有组件
import TestInput from './components/TestInput.vue'
// 所有组件列表
const components = {
TestInput
}
// 定义install方法,接收Vue作为参数
const install = function (Vue) {
// 判断是否安装,安装过就不继续往下执行
if (install.installed) return
install.installed = true
// 遍历注册所有组件
components.map((component) => Vue.use(component))
}
// 检测到Vue才执行,毕竟我们是基于Vue的
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default{
...components,
// 所有组件,必须具有install,才能使用Vue.use()
install
}
vue-demo-one
package.json
中 main
的路径是lib.js
的路径vscode
中 输入
组件就可以使用<template>
<div>
<h1>测试页面h1>
<input-one :test="test">input-one>
<h2>测试引入的组件h2>
<test-input>test-input>
div>
template>
<script>
// eslint-disable-next-line import/no-duplicates
import Test from 'vue-demo-two'
// eslint-disable-next-line import/no-duplicates
import strTwo from 'vue-demo-two'
// eslint-disable-next-line import/no-duplicates
import { one, two } from 'vue-demo-two'
import TestInput from '../../../vue-demo-one/src/components/TestInput.vue'
export default {
components: { TestInput },
data: function () {
return {
test: '张三'
}
},
methods: {
testOne () {
console.log(Test.strOne)
console.log(strTwo)
one()
two()
}
},
created () {
this.testOne()
}
}
script>
npm config set registry https://registry.npmjs.org/
package.json
主要信息"private": false,
// 使用自己的打包配置文件
"build": "node build/build.js",
// 构建生成js
"main": "lib/index.js",
"files": ["/lib/*"],
vue-cli
脚手架项目默认打包的配置配置了 mainifest.js vendor.js app.js
这些文件的配置,可以使用,也可以自己定义打包的配置js
,构建的js
的地址entry: './src/lib.js',
output: {
path: path.resolve(__dirname, '../lib'),
filename: 'index.js',
chunkFilename: '[id].js',
library: 'DemoTwo',
libraryTarget: 'umd',
libraryExport: 'default',
umdNamedDefine: true
},
npm run build
看是否构建成功,如果构建成功npm publish
命令将包发布到远端仓库npm remove
:先排除本地测试的包npm install vue-demo-two
:重新安装从远端仓库拉去最新的使用import Test from 'vue-demo-two'
import strTwo from 'vue-demo-two'
import { one, two } from 'vue-demo-two'
vue-demo
和 vue-demo-two
main
:构建输出的js
的地址"main": "lib/main.js",
"files": [
"lib/*"
],
"private": false,
npm scripts
"scripts": {
"build-lib": "node build/build-lib.js --report"
}
使用vue-cli
脚手架新建的工程,排除一下没用的配置
build-lib.js
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.lib.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
webpack.lib.conf
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.lib.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
entry: './src/lib.js',
// 配置输出构建位置
output: {
path: path.resolve(__dirname, '../lib'),
filename: '[name].js',
chunkFilename: '[id].js',
library: 'DemoTest',
libraryTarget: 'umd',
libraryExport: 'default',
umdNamedDefine: true
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new ExtractTextPlugin({
filename: 'css/[name].css',
allChunks: true
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
webpack.base.lib.conf
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
context: path.resolve(__dirname, '../'),
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src')
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
<template>
<div>
<el-input placeholder="我是测试组件" v-model="inputvalue" >el-input>
div>
template>
<script>
export default{
name: 'my-test-input',
props: {
test: String
},
data: function () {
return {
inputvalue: '123'
}
},
computed: {
}
}
script>
index.js
// 导入组件,组件必须声明 name
import MyTestInput from './TestInput.vue'
// 为组件提供 install 安装方法,供按需引入
MyTestInput.install = function (Vue) {
console.log('导出组件的名称为:'+MyTestInput.name)
Vue.component(MyTestInput.name, MyTestInput)
}
// 默认导出组件
export default MyTestInput
lib.js
// 导出所有组件
import MyTestInput from './components/TestInput.vue'
// 所有组件列表
const components = [
MyTestInput
]
// 定义install方法,接收Vue作为参数
const install = Vue => {
if (install.installed) { return }
install.installed = true
components.map(component => { Vue.component(component.name, component) })
}
// 判断是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default{
install,
...components
}
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
// 引入elementui
import 'element-ui/lib/theme-chalk/index.css'
import MyTestInput from './lib'
Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.use(MyTestInput)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ' '
})
使用webpack
打包,在lib
下面生成相应的组件
打包成功后就可以发布使用了
vue-demo-one
最新依赖npm i vue-demo-one
main.js
import MyTestInput from 'vue-demo-one'
Vue.use(MyTestInput)
test.vue
直接使用
<template>
<div>
<h1>测试页面h1>
<input-one :test="test">input-one>
<h2>测试引入的组件h2>
<my-test-input>my-test-input>
div>
template>
<script>
// eslint-disable-next-line import/no-duplicates
import Test from 'vue-demo-two'
// eslint-disable-next-line import/no-duplicates
import strTwo from 'vue-demo-two'
// eslint-disable-next-line import/no-duplicates
import { one, two } from 'vue-demo-two'
export default {
components: {},
data: function () {
return {
test: '张三'
}
},
methods: {
testOne () {
console.log(Test)
console.log(strTwo)
one()
two()
}
},
created () {
this.testOne()
}
}
script>
完整代码地址见 https://gitee.com/Marlon_Brando/qianduanxuexi