【小技巧】webpack項目中使用grunt監聽文件變動自動打包編譯
分享背景:編寫npm插件的時候,在項目裏的測試html文件內引用需要從入口文件轉譯打包成ES5。因此測試時每次改動都需要手動需要npm run build一下,很麻煩。獲知grunt有個watch功能,折騰了一下,可以做到每次js文件改動時自動build一波,很靈性。
安裝依賴包
//安裝grunt
npm i grunt --save-dev
//grunt-contrib-watch,用於監聽文件變化
npm i grunt-contrib-watch --save-dev
//grunt-loadnpmtasks,用於註冊npm安裝的功能模塊
npm i grunt-loadnpmtasks --save-dev
//grunt-webpack,用於在grunt中運行webpack配置
npm i grunt-webpack --save-dev
編寫Gruntfile.js配置文件
module.exports = function(grunt) {
grunt.initConfig({
// 配置一個webpack打包任務,其實就是跟普通的配置文件一樣,具體內容因項目而異
webpack: {
home: {
// entry要填系統的文件路徑,謹記
entry: '/Users/***************************************************************/index.js',
output: {
// 同entry
path: '/Users/********************************************************************/dist',
publicPath: './dist',
filename: 'index.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
host: '0.0.0.0',
openPage: 'http://localhost/',
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
},
watch: {
files: ['**/*.js'], // 監聽項目內所有的js文件
tasks: ['webpack:home'], //js文件變化則執行webpack任務中的home任務
options: {
livereload: true, //若是使用grunt的臨時服務器,開啓此項會自動reload頁面
}
}
});
//導入監聽功能模塊
grunt.loadNpmTasks('grunt-contrib-watch');
//導入webpack功能模塊
grunt.loadNpmTasks('grunt-webpack');
};