webpack使用闭包webpack插件代替google-closure-compiler

时间:2019-05-09 08:44:55

标签: webpack google-closure-compiler

在webpack v4之前,没有提供 closure-webpack-plugin 支持,因此我们不得不使用 google-closure-compiler 。我不确定如何使用该插件。

文件:buildSecondary.js


var ClosureCompiler = require('google-closure-compiler').compiler;

function runClosueCompiler(){
    if(!flags.compile)
      return;

    console.log('Compiling');

    var fs = require('fs');

    var closureCompiler = new ClosureCompiler({
      js: 'folder/filename.js',
      compilation_level: 'ADVANCED'
    });

    var compilerProcess = closureCompiler.run(function(exitCode, stdOut, stdErr) {
      //compilation complete 
      if(exitCode === 0){
        console.log('successful');
        fs.writeFileSync('folder/filename.min.js', stdOut);
        console.log('compiled file in folder/filename.min.js');
      }else{
        console.log('complilation exited with code '+exitCode);
        console.error(stdErr);
      }
    });
    console.log('Closure compiler executed successfully');  
}


setTimeout(function () {
  console.log('appending module.exports into file/filename.js (import fix)');
  var fs = require('fs');
  var filedata = [
    fs.readFileSync(__dirname + '/file/filename.js').toString(),
    'if(typeof module !== "undefined")',
    'module.exports = filename;'
  ];

  //append to file export
  fs.writeFileSync(__dirname + '/file/filename.js', filedata.join('\n'));

  console.log('Executing closure compiler');
  runClosureCompiler();
}, 2 * 100);

文件:webpack.config.js


var Webpack = require('webpack');
var path = require('path');
const ClosurePlugin = require('closure-webpack-plugin');
module.exports = {

    entry: './folder/entry_file.js',

    output: {
        path: path.join(__dirname, 'folder'),
        filename: 'filename.js',
    },

    module: {
        rules: [
            {
                // Target Files
                // test: /\.js?$/g,

                // Excluded folders
                exclude: /(node_modules|bower_components)/,

            },
        ]
    },
    optimization: {
        minimize: true,
        minimizer: [
            new ClosurePlugin({ mode: 'STANDARD'} , 
            { compilation_level: "ADVANCED" })
        ]
    },
    plugins: [
        new Webpack.LoaderOptionsPlugin({
            debug: true
        }),


    ],
};  

我不确定在webpack.config.js中应该进行哪些更改以构建类似于buildSecondary.js的文件。

2 个答案:

答案 0 :(得分:2)

closure-webpack-plugin has a Webpack v3 version

我像这样用大口吃

webpack.conf.js

const ClosurePlugin = require('closure-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
  devtool: 'eval-source-map',
  entry: {
    main: './src/global/js/app',
  },
  resolve: {extensions: ['.js']},
  output: {
    filename: 'js/[name].min.js',
    path: path.resolve(__dirname, 'src', 'static')
  },
  plugins: [
    new ClosurePlugin({
      mode: 'NONE',
      closureLibraryBase:
          require.resolve('google-closure-library/closure/goog/base'),
      deps: [
        require.resolve('google-closure-library/closure/goog/deps'),
        './.tmp/deps.js',
      ],
      extraDeps
    },
        devFlags),
  ],
};

gulpfile.js(部分)

const gulp = require('gulp');
const webpackConfig = require('../webpack.config.js');
const closureDeps = require('gulp-google-closure-deps');
// You'll want to connect isDevMode with your build system.
const isDevMode = true; 
const closureDir = path.dirname(
    require.resolve('google-closure-library/closure/goog/base'));

gulp.task('js', ['deps'], () => {
  // If we are in dev mode, do the uncompiled setup.
  if (isDevMode) {
    return gulp.src('')   // Source files have been configred in Webpack
        .pipe(webpack(webpackConfig))
        .pipe(gulp.dest('.'));  // Output files to public folder
  }
});
gulp.task('deps', function() {
  return gulp.src(['src/**/js/**/*.js'])
      .pipe(closureDeps({
        'closurePath': closureDir,
        prefix: '../../../..',
        baseDir: '.'
      }))
      .pipe(rename('deps.js'))
      .pipe(gulp.dest('.tmp'));
});

答案 1 :(得分:0)

让webpack识别goog.require,goog.provide,goog.module和goog.declareModuleId,您可以尝试使用此google-closure-library-webpack-plugin