Commit d44adc39 by 汤文兵

Initial commit

parents
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": [
"transform-vue-jsx",
"transform-runtime",
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
/build/
/config/
/dist/
/*.js
/src/device-config.js
/src/device-mot.js
\ No newline at end of file
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
'comma-dangle': 'off',
'semi': 'off',
'no-undef': 'off',
'no-tabs': 'off',
// allow async-await
'generator-star-spacing': 'off',
'space-before-function-paren': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
node_modules
dist
.idea
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {},
"postcss-aspect-ratio-mini": {},
"postcss-write-svg": {
utf8: false
},
"postcss-cssnext": {},
"postcss-px-to-viewport": {
// viewportWidth: 750, //视窗的宽度,对应的是我们设计稿的宽度,一般是750
// viewportHeight: 1334, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
viewportWidth: 375, //视窗的宽度,对应的是我们设计稿的宽度,一般是750
viewportHeight: 667, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除)
viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw
selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
mediaQuery: false // 允许在媒体查询中转换`px`
},
"postcss-viewport-units":{},
"cssnano": {
preset: "advanced",
autoprefixer: false,
"postcss-zindex": false
},
}
}
# demo
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
'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.prod.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, // if you are using ts-loader, setting this to true will make typescript errors show up during build
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'
))
})
})
'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
const request = require('request');
const path = require('path')
const fs = require('fs')
const methods = {
// 获取埋点 B 位
getSpmB(PK) {
return new Promise((resolve, reject) => {
const url = 'https://iot.aligenie.com/getSpmConfig?parmsData={%22spmId%22:null,%22spma%22:%22a2owj%22,%22spmb%22:null,%22isRegexpUrl%22:%22N%22,%22wlPageUrl%22:'+PK+',%22is_regexp_url%22:%22ailabs-iot.aligenie.com%22,%22appFrom%22:%22ai-open-iot%22,%22pageName%22:%22PK: '+PK+'%22,%22pageDesc%22:%22pageDesc%22,%22isEdit%22:%22Y%22,%22insertUserId%22:%2279411%22,%22pageUrl%22:%22https://ailabs-iot.aligenie.com/'+PK+'/0.0.1/dist/index.html%22,%22id%22:null,%22class%22:%22com.taobao.dw.aplus.entity.spm.Spmb%22}&id=79411'
request.get(url, function(error, response, body) {
body = JSON.parse(body)
if (!error && response.statusCode == 200 && body.spmb) {
return resolve(body.spmb)
}
resolve()
})
})
},
// 判断是否已经埋点
needSpma() {
return new Promise((resolve, reject) => {
fs.readFile(path.resolve(__dirname, '../index.html'),'utf-8', (err, data) => {
if (err) return console.log('readFile error:', err)
if (data.indexOf('data-spm') > -1 && data.indexOf('aplus_wap') > -1) {
resolve(false) // 不需要埋点 因为已经埋好了
} else {
resolve(true)
}
})
})
},
// 注入埋点
insertSpmInfo(spmb) {
return new Promise((resolve, reject) => {
fs.readFile(path.resolve(__dirname, '../index.html'),'utf-8', (err, data) => {
if (err) return console.log('readFile error:', err)
const html = data.split('\n')
let insertKey = ''
let insertJsKey = ''
html.map((val, key) => {
if (val.indexOf('</head') > -1) {
insertKey = key
}
if (val.indexOf('<body') > -1) {
insertJsKey = key + 2
}
// 注入 spmb 到 body
if (val.indexOf('<body') > -1) {
html.splice(key, 1, val.replace('<body', `<body data-spm="${spmb}"`))
}
return val
})
html.splice(insertKey, 0, ' <meta content="a2owj" name="data-spm" />')
html.splice(insertJsKey, 0, ` <script type="text/javascript" id="beacon-aplus" src="https://g.alicdn.com/alilog/mlog/aplus_wap.js" exparams="clog=o&aplus&sidx=aplusSidx&ckx=aplusCkx"></script>`)
fs.writeFile(path.resolve(__dirname, '../index.html'), html.join('\n'), 'utf-8', function (err) {});
})
})
},
// 获取PK值
getProdcutKey() {
return new Promise((resolve, reject) => {
fs.readFile(path.resolve(__dirname, '../src/device-config.js'),'utf-8', (err, data) => {
if (err) return console.log('readFile error:', err)
const pk = methods.getDataVal(data, 'productKey')[0]
this.prodcutKey = pk
if (!pk) {
console.error(`
请先设置你开发的设备的prodcutKey(必填):
设置路径 /src/device-config.js -> debug.params.prodcutKey \n
open平台地址:https://iot.aligenie.com/home
是open平台产品信息中的Product ID \n
`)
return
}
resolve(pk)
})
})
},
// 获取参数的值
getDataVal(data, key) {
data = data.slice(data.indexOf(key))
data = data.split('\n')[0]
var single = data.match(/\'\w*\'/g) || [];
var double = data.match(/\"\w*\"/g) || [];
return [...single, ...double].map(function(element){
return element.slice(1, -1);
});
}
}
module.exports = methods
\ No newline at end of file
require('shelljs/global')
const ora = require('ora')
const { getProdcutKey, getSpmB, needSpma, insertSpmInfo } = require('./make-method.js')
class setSpm {
constructor() {
this.run()
}
async run() {
// 判断是否已经埋点
const spmaStatus = await needSpma()
if (spmaStatus) {
const PK = await getProdcutKey() // 校验是否有 PK
const spmb = await getSpmB(PK) // 获取spmb
// 注入埋点
spmb && insertSpmInfo(spmb)
}
const spinner = ora('正在打包项目,请稍等...')
spinner.start()
exec('node build/build.js')
spinner.stop()
}
}
new setSpm()
\ No newline at end of file
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
'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, '../'),
entry: {
app: './src/main.js'
},
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('[name].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const OpenBrowserPlugin = require('open-browser-webpack-plugin')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
// inline: false,
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
disableHostCheck: true
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
const url = `http://test.open-iot.tmall.com:${port}`;
const listUrl = `https://ailabs-iot.aligenie.com/2364/1.0.16/dist/index.html#/?_ali_share_button_=false&debugUrl=${url}`;
//const listUrl = `https://ailabs-iot.aligenie.com/2364/1.0.16/dist/index.html#/?debugUrl=${url}`;
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [
`listUrl is running here: ${listUrl}`,
`Your application is running here: ${url}`,
],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined,
clearConsole: false
}))
devWebpackConfig.plugins.push(new OpenBrowserPlugin({ url: listUrl }))
resolve(devWebpackConfig)
}
})
})
'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.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-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 = 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,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('[name].js'),
chunkFilename: utils.assetsPath('[id].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('[name].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
/*
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
*/
// // extract webpack runtime and module manifest to its own file in order to
// // prevent vendor hash from being updated whenever app bundle is updated
/*
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
This instance extracts shared chunks from code splitted chunks and bundles them
in a separate chunk, similar to the vendor chunk
see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
*/
/*
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
*/
// copy custom static assets
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
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: '',
assetsPublicPath: './',
/**
* Source Maps
*/
productionSourceMap: false,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<meta name="msapplication-tap-highlight" content="no" />
<meta id="stopUsePullRefresh" value="true">
<meta id="WV.Meta.DisableRefresh" value="true" />
<meta id="WV.Meta.StopBounces" value="true" />
<title></title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
{
"name": "food",
"version": "1.0.1",
"description": "",
"author": "汤文兵<>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"lint": "eslint --ext .js,.vue src",
"build": "node build/make-spm.js"
},
"dependencies": {
"cssnano": "^4.1.10",
"genie-sdk": "^1.1.0",
"genie-common-sdk": "^1.0.0",
"genie-ui": "^1.1.0",
"postcss-aspect-ratio-mini": "^1.0.1",
"postcss-cssnext": "^3.1.0",
"postcss-px-to-viewport": "^1.1.0",
"postcss-viewport-units": "^0.1.6",
"postcss-write-svg": "^3.0.1",
"viewport-units-buggyfill": "^0.6.2",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vuex": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^7.2.3",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-component": "^1.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.11",
"cssnano-preset-advanced": "^4.0.7",
"eslint": "^4.15.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"node-notifier": "^5.1.2",
"node-sass": "^4.9.3",
"open-browser-webpack-plugin": "0.0.5",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.1.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.3.2",
"rimraf": "^2.6.0",
"sass-loader": "^7.1.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
\ No newline at end of file
<template>
<div id="appview">
<iot-header :data='navBarData'></iot-header>
<router-view/>
</div>
</template>
<script>
import { mapState } from 'vuex';
import { IotHeader } from 'genie-ui';
export default {
name: 'App',
components: {
IotHeader
},
created: function () {
this.$store.dispatch('deviceStatusChange')
},
computed: {
...mapState({
navBarData: state => state.base.navBarData
})
},
}
</script>
<style lang="less" >
@import './assets/less/style.less';
@import 'genie-ui/build/tunas.css';
html,
body {
margin: 0;
height: 100%;
}
</style>
// 使用 px 转 vm 功能的副作用 问题:content会引起部分浏览器下,图片不会显示 所以要加该样式
img{
content: initial !important;
}
#appview {
height: 100%;
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #fafafa;
box-sizing: border-box;
font-size: 14px;
&.hasH5bar{
padding-top: 44px;
}
}
.page{
display: inline-block;
width: 100%;
height: 100%;
padding-bottom: 10px;
background-color: #f4f6f7;
box-sizing: border-box;
}
\ No newline at end of file
/*
* 重置默认样式
* */
/* CSS Document */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
abbr,article,aside,audio,canvas,datalist,details,figure,footer,hgroup,header,mark,menu,meter,nav,output,progress,section,time,video{
margin: 0;
padding: 0;
border: 0;
outline: 0;
font: inherit;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
.article,aside,audio,canvas,datalist,details,figure,footer,hgroup,header,mark,menu,meter,nav,output,progress,section,time,video{
display: block;
}
body {
line-height: 1;
}
ol, ul ,li{
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before,blockquote:after,
q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
legend{
display:none;
}
img{ vertical-align: middle;}
input,button{
overflow:visible;
margin: 0;
padding: 0;}
a{
text-decoration: none;
}
\ No newline at end of file
@import './reset.less';
@import './public.less';
\ No newline at end of file
export default {
base: {
env: 'dev',
platform: 'genie',
icon: [],
debugVConsole: false,
deviceInfo: {}
},
debug: {
stagingMap: 'release',
params: {
productKey: '12366',
// prodcutKey: '12366',
devId: ''
}
}
}
import { connect } from 'genie-sdk'
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import store from './store'
import deviceConfig from './device-config'
// px 转 vm
import viewportUnitsBuggyfill from 'viewport-units-buggyfill'
var hacks = require('viewport-units-buggyfill/viewport-units-buggyfill.hacks');
viewportUnitsBuggyfill.init({
hacks
})
Vue.use(Vuex)
Vue.config.productionTip = false
connect(Vue, {
el: '#app',
router,
store,
components: { App },
template: '<App/>',
deviceConfig
})
<template>
<div class="main">
<!-- 设备信息 -->
<div class="deviceInfo">
<img :src="productInfo.img">
<h5 class="title">{{productInfo.title}}</h5>
</div>
<!-- 设备状态 -->
<push-bar
v-for="(val, key) in deviceStatus" v-bind:key="key"
:data="val" :type="val.type"
:check="val.check"
>
</push-bar>
</div>
</template>
<script type="text/ecmascript-6">
import { mapState } from 'vuex';
import { PushBar } from 'genie-ui';
export default {
name: 'Main',
components: {
PushBar
},
data() {
return {};
},
computed: {
...mapState({
// 产品信息详情
productInfo: state => {
return state.base.productInfo;
},
// 设备status
deviceStatus(state) {
const attr = state.publicInfo.attr;
const onlinestate = attr.onlinestate === 'online' ? '在线' : '离线';
const powerstate = attr.powerstate === 1;
return [{
text: '设备状态',
descColor: '#4a4a4a',
desc: onlinestate
}, {
check: powerstate,
text: '开关状态',
type: 'switch',
clickBack: (val) => {
this.$store.dispatch('setDeviceStatus', {
powerstate: val.check ? 0 : 1
});
}
}]
},
// 在线状态
onlinestate: state => {
const onlinestate = state.publicInfo.attr.onlinestate;
return onlinestate === 'online' ? '在线' : '离线';
},
// 开关状态
powerstate: state => {
const powerstate = state.publicInfo.attr.powerstate;
return powerstate === 1;
},
}),
},
created() {
console.log('this.$route.query:', this.$route.query);
this.$nextTick(() => {
this.setNavbar(); // 设置topbar
});
AI.aiRequestMtopProxy({
api: 'mtop.alibaba.aicloud.recipe.getRecomandRecipePage',
data: {
devId: this.$route.query.devId, // 参数示例
productKey: '12366', // 参数示例
params: {
openAccountId: '1335029947044189'
}
}
}).then((res) => {
console.log('返回信息', res);
}).catch((res) => {
console.log('失败返回', res);
});
},
beforeDestroy() {
AI.allListenRemove(); // 页面兼听事件取消
},
methods: {
// 设置topbar
setNavbar() {
AI.setNavbar({
title: this.productInfo.title,
})
},
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.deviceInfo {
display: flex;
height: 180px;
margin-bottom: 10px;
background-color: #fff;
flex-direction: column;
align-items: center;
justify-content: center;
img {
height: 80px;
}
.title {
color: #4a4a4a;
font-weight: bold;
padding-top: 5px;
}
}
</style>
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/page/main/index'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Main',
component: Main
}
]
})
import Vue from 'vue'
import Vuex from 'vuex'
import publicInfo from './modules/public' // 公共vuex
Vue.use(Vuex)
/* eslint-disable no-new */
export default new Vuex.Store({
modules: {
publicInfo
}
})
/* eslint-disable no-new */
export default {
state: {
status: 0, // 设备状态 0 - 未激活, 1 - 在线, 3 - 离线, 8 - 禁用,
attr: {}, // 设备属性
errorInfo: {}, // 设备上报的错误信息
scheduleInfo: {} // 即将到来的定时,倒计时信息
},
mutations: { // 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation, 只能同步
/**
* 更新状态树中的设备相关状态
* @param {object} payload.data 新的数据
*/
updateDeviceStatus(state, payload) {
const { data } = payload
const { status, attr = {}, errorInfo = {}, scheduleInfo = {} } = data
if (status !== undefined) state.status = status
state.attr = Object.assign({}, state.attr, attr)
state.errorInfo = errorInfo
state.scheduleInfo = scheduleInfo
},
/**
* 更新状态树中的属性集合
* @param {*} attr 要更新的属性集合
*/
updateDeviceAttr(state, attr = {}) {
state.attr = Object.assign({}, state.attr, attr)
}
},
actions: {
/**
* 获取设备状态
*/
deviceStatusChange({ commit }) {
AI.deviceStatusChange({
callback: resp => {
// console.log('长链接返回的设备状态:', Object.assign({}, resp.model));
// 更新设备状态
commit('updateDeviceStatus', { data: resp.model })
},
errorCallback: (error) => { console.log('stateChange ERROR:', error) }
});
},
/**
* 设置设备属性
* @param {*} attrs 需要设置的属性集合
*/
setDeviceStatus({ state, commit }, attrs) {
if (state.attr.onlinestate !== 'online') {
console.error('**设备不在线 无法操控**')
return;
}
// 更新数据
commit('updateDeviceStatus', { data: {
attr: attrs
}})
// 设置数据
AI.setDeviceStatus(attrs).then((resp) => {
console.log('setDeviceStatus:', resp)
}).catch((err) => {
console.log(err)
})
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment