webpack項目中使用grunt監聽文件變更自動打包編譯

【小技巧】webpack項目中使用grunt監聽文件變更自動打包編譯

分享背景:編寫npm插件的時候,在項目裏的測試html文件內引用須要從入口文件轉譯打包成ES5。所以測試時每次改動都須要手動須要npm run build一下,很麻煩。獲知grunt有個watch功能,折騰了一下,能夠作到每次js文件改動時自動build一波,很靈性。javascript

安裝依賴包

//安裝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');
};
相關文章
相關標籤/搜索