问题
I'm trying to understand how to build a component with Gulp. At this time, I have a Vue component that looks like this:
my-component.vue
<template>
<div class="foo">
</div>
</template>
<script>
export default {
data() {
return {};
},
props: {
message: {
type: String,
default: ''
}
},
methods: {
display: function() {
alert(this.message);
}
},
};
</script>
I'm building this component via Gulp. My gulpfile.js has the following:
gulpfile.js
const gulp = require('gulp');
const vueify = require('gulp-vueify2');
gulp.task('default', ['build']);
gulp.task('build', function() {
return gulp.src('./src/my-component.vue')
.pipe(vueify())
.pipe(gulp.dest('./deploy'))
;
});
When I run this, I have my-component.js in the "deploy" directory. When I view that file, I see the following at the top of my-component.js
var __vueify_style_dispose__ = require("vueify/lib/insert-css")
I'm trying to load the component in an HTML file like this:
<script type="text/javascript" src="./my-component.js"></script>
The script loads. However, there is an error in the console that says:
Uncaught ReferenceError: require is not defined
How do I build the component such that require
is not used? Is there a way to do this? If so, how?
回答1:
Okay I did find something without the need of any require module. That's a bit ugly so you may not like it.
Step 1:
Extract CSS in gulpfile.js
.
const gulp = require('gulp');
const vueify = require('gulp-vueify2');
gulp.task('default', ['build']);
gulp.task('build', function() {
return gulp.src('./src/my-component.vue')
.pipe(vueify({
extractCSS: true,
CSSOut: './deploy/bundle.css'
}))
.pipe(gulp.dest('./deploy'))
;
});
Step 2: Your component, my-component.vue
.
<template>
<div class="foo">
World
</div>
</template>
<script>
module.exports = {
data() {
return {};
},
props: {
message: {
type: String,
default: ''
}
}
};
// Well, hu, you have no module so just keep your component somewhere.
window.vueComponents['my-component'] = module.exports;
</script>
<style>
.foo {
color: red;
}
</style>
Step 3: The index.html
.
<html>
<head>
<link rel="stylesheet" type="text/css" href="/bundle.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<script>
window.module = {}; // Yeah just avoid the error as you have no module
window.vueComponents = {}; // Global register of your components...
</script>
<script src="./my-component.js"></script>
</head>
<body>
<div id="app">
<div>
{{ foo }}
<my-component></my-component>
</div>
</div>
<script>
new Vue({
// Here you give your component to your vue instance
components: window.vueComponents,
data() {
return {
foo: 'Hello'
};
},
el: '#app'
});
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/44521672/gulp-compiling-vue-component-without-require