我正在使用Vue。这就是我在gulpfile中构建的方式:
browserify('./main.js')
.transform(vueify)
.bundle()
.pipe( fs.createWriteStream('./build/bundle.js') );
问题是vueify无法处理我的.js文件中的es6导出。它只适用于.vue组件。它适用于module.exports
,但我想利用.js文件中的es6代码。
当调用bundle()
时,我当前得到错误:
'import' and 'export' may appear only with 'sourceType: module'
有没有什么方法可以修改gulpfile来处理使用我的.vue组件正在导入的es6的js文件?
经过几个小时的挣扎,我终于想通了。
- 安装babelify:
npm install --save-dev babelify
- 将其添加到您的gullfile的顶部:
var babelify = require( 'babelify' )
-
添加
.transform( babelify )
:return browserify('./main.js') //tells browserify where to start, but doesn't run the resolve algorithm yet .transform( vueify ) //executes vueify to transform vue components to js .transform( babelify ) //executes babelify to transform es6 to es5 .bundle() //runs the module resolve algorithm on all the require() statements .pipe( fs.createWriteStream('./build/bundle.js') );
好吧,我已经遇到这个问题好几天了,试图让Axios与Vue合作,而OP的自我回答救了我。话虽如此,我还没有使用Gulp,必须执行几个不同的步骤。
我的问题实际上是import
命令。它将在Browserify编译期间出错,并且在运行时出现错误axios is undefined
。
我的.vue文件的脚本部分如下:
<script>
import axios from 'axios';
module.exports = {
name: "address-search",
data: function() {
return {
valid: false,
hash: '',
errors: []
}
},
methods: {
async validateAddress() {
const query = `./validateAddress/` + this.hash;
try {
const response = await axios.get(query);
this.valid = response.data;
} catch (e) {
this.errors.push(e)
}
}
}
}
</script>
我的捆绑包命令如下所示:
browserify -t vueify -e public/javascripts/main.js -o public/javascripts/bundle.js
在编译期间,我收到了OP:所述的错误
'import' and 'export' may appear only with 'sourceType: module'
我采取的步骤包括:
- 安装babel内核:
npm install --save-dev babel-core
- 安装babelify(根据OP):
npm install --save-dev babelify
- 安装bable-preset-es2015:
npm install --save-dev babel-preset-es2015 babel-plugin-transform-runtime
- 重新运行
browserify -t vueify -e public/javascripts/main.js -o public/javascripts/bundle.js
瞧现在import
指令起作用了,Axios很高兴。
回想起来,它一开始不起作用的原因是显而易见的(没有新Javascript语法的映射),但我当然希望这能帮助其他人实现业务价值,而不是在库管理上花费太多时间。