我创建了一个npm包https://www.npmjs.com/package/vue-top-down-test,它只导出两个对象VueTopDown
和VueTopDownItem
。
import { VueTopDown } from './vue-top-down'
import { VueTopDownItem } from './vue-top-down-item'
module.exports = {
VueTopDown,
VueTopDownItem
}
但是,我在演示https://github.com/MoYummy/vue-top-down/tree/master/docs/demo-node中未能使用(甚至只是打印)它们。
import * as VTD from 'vue-top-down-test'
import Vue from 'vue'
console.log(Vue)
console.log(VTD)
有人能给我一些线索吗?感谢。
答案 0 :(得分:0)
在 webpack.config.js 中将output.libraryTarget
设为umd
。默认libraryTarget
设置为var
。返回值分配给变量,不能在模块
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'VueTopDown',
libraryTarget: 'umd',
umdNamedDefine: true
}
多个目标 虽然webpack不支持将多个字符串传递到target属性,但您可以通过捆绑两个单独的配置来创建同构库:Multiple Targets
const path = require('path');
const serverConfig = {
target: 'node',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'lib.node.js'
}
//…
};
const clientConfig = {
target: 'web', // <=== can be omitted as default is 'web'
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'lib.js'
}
//…
};
module.exports = [ serverConfig, clientConfig ];
修改webpack.config.js
供您参考
const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const serverConfig = {
mode: 'production',
target: 'node',
entry: {
'vue-top-down': './src/index.js',
'vue-top-down.min': './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'VueTopDown',
libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env']
}
}]
},
stats: {
colors: true
},
devtool: 'source-map',
optimization: {
minimizer: [
new UglifyJsPlugin({
test: /\.min\.js$/
})
]
},
plugins: [
new CleanWebpackPlugin([
path.resolve(__dirname, 'dist')
]),
]
};
const clientConfig = {
mode: 'production',
target: 'web',
entry: {
'vue-top-down': './src/index.js',
'vue-top-down.min': './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].web.js',
library: 'VueTopDown'
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env']
}
}]
},
stats: {
colors: true
},
devtool: 'source-map',
optimization: {
minimizer: [
new UglifyJsPlugin({
test: /\.min\.js$/
})
]
},
plugins: [
new CleanWebpackPlugin([
path.resolve(__dirname, 'dist')
]),
]
};
module.exports = [serverConfig, clientConfig];
答案 1 :(得分:0)
最后成功:https://github.com/MoYummy/vue-top-down/tree/v0.0.1
关键是为每个运行时环境构建commonjs
,umd
和esm
。