I am using Vue. This is how I'm building in my gulpfile:
browserify('./main.js')
.transform(vueify)
.bundle()
.pipe( fs.createWriteStream('./build/bundle.js') );
The problem is vueify doesn't handle the es6 exports in my .js files. It only works in .vue components. It works with module.exports
, but I'd like to take advantage of es6 code in my .js files.
When bundle()
is called, I currently get the error:
'import' and 'export' may appear only with 'sourceType: module'
Is there any way to modify the gulpfile to handle js files using es6 that my .vue components are importing?
After hours of struggling, I finally figured it out.
npm install --save-dev babelify
var babelify = require( 'babelify' )
;Add .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') );
OK, I've been running into this for several days trying to get Axios to work with Vue and the OP's self-answer saved me. That being said, I'm not using Gulp (yet) and had to do several different steps.
My problem was actually with the import
command. It would error during the Browserify compile and at runtime the error axios is undefined
was ocurring.
The script section of my .vue file is as follows:
<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>
My bundle command is as follows:
browserify -t vueify -e public/javascripts/main.js -o public/javascripts/bundle.js
And during compile I was getting the error stated by the OP:
'import' and 'export' may appear only with 'sourceType: module'
The steps I took included:
npm install --save-dev babel-core
npm install --save-dev babelify
npm install --save-dev babel-preset-es2015 babel-plugin-transform-runtime
browserify -t vueify -e public/javascripts/main.js -o public/javascripts/bundle.js
Voila! Now the import
directive works and Axios is happy.
In retrospect, it is somewhat obvious why it didn't work in the first place (no mapping for the newer Javascript syntax) but I certainly hope this helps someone else get to delivering business value instead of spending too much time on library management.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With