vue-browserify将yaml文件作为javascript对象vuejs2导入

时间:2018-10-14 17:00:40

标签: vue.js yaml browserify

我将vuejs2与browserify(https://github.com/vuejs-templates/browserify)配合使用

我尝试使用YAML文件

我想尝试其他方法来导入.yml文件:

1)直接像json文件一样导入。因此,我不必在生产中提供yaml文件:

import Data from '../static/data.yml'

2)从外部URL导入(这样,我无需重新构建即可更改应用程序上的数据):

3)保存时将YML转换为JSON

实际上,在Webpack中找到了很多解决方案,但在browserify中却找不到

有我的package.json文件

{
  "name": "vuejs-browserify-yaml",
  "version": "0.1.0",
  "description": "A Vue.js project",
  "author": "John DOE <john.doe@gmail.com>",
  "private": true,
  "scripts": {
    "watchify": "watchify -vd -p browserify-hmr -e src/main.js -o dist/build.js",
    "serve": "http-server -o -c 1 -a localhost",
    "dev": "npm-run-all --parallel watchify serve",
    "lint": "eslint --ext .js,.vue src",
    "build": "cross-env NODE_ENV=production browserify -g envify -p [ vueify/plugins/extract-css -o dist/build.css ] -e src/main.js | uglifyjs -c warnings=false -m > dist/build.js"
  },
  "browserify": {
    "transform": [
      "babelify",
      "vueify"
    ]
  },
  "browser": {
    "vue": "vue/dist/vue.common.js"
  },
  "dependencies": {
    "vue": "^2.0.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.0",
    "babel-plugin-transform-runtime": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "babel-preset-stage-2": "^6.0.0",
    "babel-runtime": "^6.0.0",
    "babelify": "^7.2.0",
    "browserify": "^13.1.0",
    "browserify-hmr": "^0.3.1",
    "cross-env": "^2.0.0",
    "envify": "^3.4.1",
    "eslint": "^3.3.0",
    "eslint-config-standard": "^5.3.5",
    "eslint-plugin-html": "^1.5.2",
    "eslint-plugin-promise": "^2.0.1",
    "eslint-plugin-standard": "^2.0.0",
    "http-server": "^0.9.0",
    "npm-run-all": "^2.3.0",
    "proxyquireify": "^3.0.1",
    "uglify-js": "^2.5.0",
    "vueify": "^9.0.0",
    "watchify": "^3.4.0"
  }
}

1 个答案:

答案 0 :(得分:0)

在各种论坛上花了很多时间之后,我找到了解决方法

1)直接像json文件一样导入。因此,我不必在生产中提供yaml文件:

首先安装yamlify

npm install --save-dev yamlify

然后将yamlify添加到browserify转换

"browserify": {
    "transform": [
      "babelify",
      "vueify",
      "yamlify"
    ]
  },

最后将您的YAML作为经典的json文件导入(例如在main.js中)

import Data from '../static/example-data.yml'

2)从外部网址导入

首先安装yamljs

npm install --save-dev yamljs

然后您可以获取诸如此类的外部文件数据

import YAML from 'yamljs'
const ExternalData = YAML.load('http://localhost:8080/static/example-data.yml')
console.log(ExternalData)

3)保存时将YML转换为JSON 首先安装yamljs

npm install --save-dev yamljs

然后在package.json上更新脚本(添加yml2json并更新watchify)

"scripts": {
    "watchify": "watchify -vd -p browserify-hmr -e src/main.js -o dist/build.js | npm run yaml2json",
    "yaml2json": "yaml2json static -r -s -w",
    "serve": "http-server -o -c 1 -a localhost",
    "dev": "npm-run-all --parallel watchify serve",
    "lint": "eslint --ext .js,.vue src",
    "build": "cross-env NODE_ENV=production browserify -g envify -p [ vueify/plugins/extract-css -o dist/build.css ] -e src/main.js | uglifyjs -c warnings=false -m > dist/build.js"
  },