webpack использует closure-webpack-plugin вместо google-closure-compiler - PullRequest
2 голосов
/ 09 мая 2019

До выпуска 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.

1 Ответ

2 голосов
/ 09 мая 2019

closure-webpack-plugin имеет версию Webpack v3

Я использую это с глотком, как это

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'));
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...