一、配置文件package.json
{ "name": "vuetest", "version": "1.0.0", "description": "", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "server": "webpack-dev-server --open", "build": "webpack-dev-server" }, "author": "camille", "license": "ISC", "devDependencies": { "babel-core": "^6.26.0", "babel-helper-define-map": "^6.26.0", "babel-helper-optimise-call-expression": "^6.24.1", "babel-helper-vue-jsx-merge-props": "^2.0.2", "babel-loader": "^7.1.2", "babel-plugin-syntax-jsx": "^6.18.0", "babel-plugin-transform-vue-jsx": "^3.5.0", "babel-preset-es2015": "^6.24.1" } }
devDependencies这一项最初没有,是在后续步骤中,安装插件时,通过命令自动添加的。
二、新建文件
1、index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vuejsx</title> </head> <body> <div id="J_vapp_jsx"></div> <script type="text/javascript" src="https://unpkg.com/vue"></script> <script type="text/javascript" src="bundle.js"></script> </body> </html>
2、webpack.config.js
module.exports = { entry: './myvu.js', output: { path: __dirname, filename: 'bundle.js' }, devtool: "inline-source-map", module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader'] } ] } }
3、.babelrc
{ "presets": ["es2015"], "plugins": ["transform-vue-jsx"] }
4、myvu.js
var vm = new Vue({ el: '#J_vapp_jsx', data: { msg: 'Hello JSX' }, methods: { hello () { alert('Hello Vue 2.0') } }, render (h) { const data = { attrs: { id: 'J_div' }, on: { click: () => { console.log('点击状态:点击啦!') } }, props: { innerHTML: 'hihihi' }, hook: { insert: () => { console.log('dom插入状态:已经插入。') } } } // return <div title="一个div" {...data}/> return ( <div id="J_jsx_box"> <button class={{ cls1: true, cls2: true }} style={{fontSize: '15px'}} on-click={this.hello} {...data}> {this.msg} </button> </div> ) } })
三、安装相关插件
cnpm i -D xxx
xxx包含babel-plugin-syntax-jsx,babel-plugin-transform-vue-jsx,babel-helper-vue-jsx-merge-props,babel-core,babel-loader,babel-preset-es2015。
为什么会在package.json中看到babel-helper-define-map和babel-helper-optimise-call-expression,这是我在调试的时候,自己加上去的,也要安装,然后就不报错了。github上的vue作者写的文档有些问题,直接运行会报错。
四、运行项目
npm run server