GithubHelp home page GithubHelp logo

hxlniada / webpack-concat-plugin Goto Github PK

View Code? Open in Web Editor NEW
97.0 4.0 55.0 614 KB

a plugin to help webpack to concat file and inject to html

Home Page: https://github.com/hxlniada/webpack-concat-plugin

JavaScript 96.19% HTML 3.81%
webpack concatenation concat legacy

webpack-concat-plugin's Introduction

webpack-concat-plugin

Build Status npm package npm downloads

A plugin to help webpack concat js and inject into html

Why

Webpack is really powerful. However, when I want to concat the static files and inject into html without webpack JSONP code wrapper, it seems impossible to do that without other tool's help.

Install

npm install webpack-concat-plugin --save-dev

for webpack >= 4.0

npm install [email protected] --save-dev

Features

  • Concat
  • Inject to html(with html-webpack-plugin)

Usage

const ConcatPlugin = require('webpack-concat-plugin');

new ConcatPlugin({
    ...see options
    // examples
    uglify: false,
    sourceMap: false,
    name: 'result',
    outputPath: 'path/to/output/',
    fileName: '[name].[hash:8].js',
    filesToConcat: ['jquery', './src/lib/**', './dep/dep.js', ['./some/**', '!./some/excludes/**']],
    attributes: {
        async: true
    }
});

Options

uglify [boolean | object] default: false

if true the output file will be uglified

or set uglifyjs options to customize the output

sourceMap [boolean] default: false

if true, will output sourcemap

name [string] default: "result"

it's useful when you want to inject to html-webpack-plugin manully

publicPath [string|boolean] default: webpack's publicPath

if set, will be used as the public path of the script tag.

if set to false, will use relativePath.

outputPath [string]

if set, will be used as the output directory of the file.

fileName [string] default: [name].js

if set, will be used as the output fileName

filesToConcat [array] required

supported path patterns:

  • normal path
  • npm packages
  • glob

injectType ["prepend"|"append"|"none"] default: "prepend"

how to auto inject to html-webpack-plugin(only if html-webpack-plugin set inject option not to be false)

attributes [object]

if set, will be used as the extra attributes of the script tag.

Examples

Inject to html by hand

doctype html
...
    script(src=htmlWebpackPlugin.files.webpackConcat.flexible)
...

TODO

  • add css support
  • auto inject to html

webpack-concat-plugin's People

Contributors

ddumont avatar filipesilva avatar gosp avatar hxlniada avatar indragunawan avatar jiverson avatar karlalnebratt avatar mrusselltombras avatar subhaze avatar tomastrajan avatar xcatliu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

webpack-concat-plugin's Issues

Line feed necessary

Sometimes concat results in a syntax error

//# sourceMappingURL=payapi-error-dialog.js.map|webpackJsonp([1],{

/***/ 1:
/***/ (function(module, exports, __webpack_require__) {

The pipe indicates where the prev file ends and new file starts

Disabling source maps solves the problem but I wanted to let you know
devtool: false,

Maybe test on the devtool flag and add a Line Feed if it's not false

Allow templating fileName

This is a feature request.

When configuring Webpack output, it is possible to specify a couple of template variables like [name].[hash].bundle.js.

In webpack-concat-plugin this is not possible, and the hash is always positioned just before .js.

I'd like to request that this be possible in the configuration, falling back to the previous behaviour if the template tags aren't found.

new ConcatPlugin({
    // ...
    useHash: true,
    name: 'flexible',
    fileName: '[name].[hash].bundle.js', // would output to 'flexible.d41d8cd98f00b204e980.bundle.js'
});

I'd like to work on this feature if you accept the idea.

Deprecation warning for Tapable.plugin

Hi there,

How can I get rid of the following deprecation warning that it seems spawn from your plugin?

(node:10584) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
    at /[MY/PATH]/node_modules/webpack-concat-plugin/release.js:150:42
    at new Promise (<anonymous>)
    at ConcatPlugin.resolveReadFiles (/[MY/PATH]/node_modules/webpack-concat-plugin/release.js:149:49)
    at ConcatPlugin.apply (/[MY/PATH]/node_modules/webpack-concat-plugin/release.js:287:18)
    at webpack (/[MY/PATH]/node_modules/webpack/lib/webpack.js:37:12)
    at processOptions (/[MY/PATH]/node_modules/webpack-cli/bin/cli.js:441:16)
    at yargs.parse (/[MY/PATH]/node_modules/webpack-cli/bin/cli.js:528:3)
    at Object.parse (/[MY/PATH]/node_modules/yargs/yargs.js:552:18)
    at /[MY/PATH]/node_modules/webpack-cli/bin/cli.js:219:8
    at Object.<anonymous> (/[MY/PATH]/node_modules/webpack-cli/bin/cli.js:530:3)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/[MY/PATH]/node_modules/webpack/bin/webpack.js:165:2)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

Stuck on 95% emitting

Hi, I can run webpack dev server fine, but when I use the same settings for webpack it is always stuck at 95% emitting webpackConcatPlugin. There are no errors it is just stuck there. Please help.

const webpack = require('webpack');
const path = require('path');
const ConcatPlugin = require('webpack-concat-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const htmlOutputPath = path.resolve(__dirname, '../../../linkmygoods/html');
const jsPath = path.resolve(__dirname, '../../js');

// const devMode = process.env.NODE_ENV !== 'production'

module.exports = {
  output: {
    filename: 'bundle.js',
    path: path.resolve(htmlOutputPath, 'Resources'),
    libraryExport: "default"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.png$/,
        include: [path.resolve(htmlOutputPath, 'images')],
        loader: 'url-loader'
      },
      {
        test: /\.svg$/,
        include: [path.resolve(htmlOutputPath, 'images')],
        loader: 'url-loader',
      },
      {
        test: /\.svg$/,
        exclude: [path.resolve(htmlOutputPath, 'images')],
        loader: 'svg-inline-loader'
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          // devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          // 'style-loader', // creates style nodes from JS strings
          {
            loader: 'css-loader', // translates CSS into CommonJS
            options: { 
              alias: {
                "../images": path.resolve(htmlOutputPath, 'images')
              } 
            }
          },
          'sass-loader' // compiles Sass to CSS
        ]
      }
    ]
  },
  resolve: {
    alias: {
      moment: path.resolve(__dirname, 'node_modules/moment/moment.js'),
      SESSION: path.resolve(jsPath, 'Util/SESSION.js'),
      'node-calendar': path.resolve(__dirname, 'node_modules/node-calendar/node-calendar.js')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      moment: 'moment',
      SESSION: 'SESSION',
      calendar: 'node-calendar'
    }),
    new ConcatPlugin({
        sourceMap: false,
        name: 'result',
        outputPath: path.resolve(htmlOutputPath, 'Resources'),
        fileName: 'legacy.js',
        filesToConcat: [
          // 'jquery',
          [
            path.resolve(jsPath, 'Util/Util.js'),
            path.resolve(jsPath, 'Util/String.js'),
            path.resolve(jsPath, 'Util/Custom.js'),
            path.resolve(jsPath, 'Util/ArrayConvertible.js')
          ],
          [
            path.resolve(jsPath, 'DBObject/Common.js'),
            path.resolve(jsPath, 'DBObject/DBObject.js'),
            path.resolve(jsPath, 'DBObject/DBFile.js'),
            path.resolve(jsPath, 'DBObject/DBObjectRegister.js'),
            path.resolve(jsPath, 'DBObject/DBObjectListRegister.js'),
            path.resolve(jsPath, 'DBObject/Item/Item.js'),
            path.resolve(jsPath, 'DBObject/Company/Company.js'),
            path.resolve(jsPath, 'DBObject/Order/Order.js'),
            path.resolve(jsPath, 'DBObject/Order/Quote.js'),
            path.resolve(jsPath, 'DBObject/Order/Shipment.js')
          ],
          [
            path.resolve(jsPath, 'Default/Handler/Handler.js'),
            path.resolve(jsPath, 'Util/Ajax.js'),
            path.resolve(jsPath, 'Util/Ajax/Currency.js')
          ],
          [
            path.resolve(jsPath, 'Default/GUI/GUIObject.js'),
            path.resolve(jsPath, 'Default/Module/Module.js'),
            path.resolve(jsPath, 'Default/Module/DefaultModule.js'),
            path.resolve(jsPath, 'Default/Module/Item/Item.js'),
            path.resolve(jsPath, 'Default/Module/Order/Common.js'),
            path.resolve(jsPath, 'Default/Module/Order/Quote.js'),
            path.resolve(jsPath, 'Default/Module/Order/Order.js'),
            path.resolve(jsPath, 'Default/Progress/Progress')
          ],
          [
            path.resolve(jsPath, 'Util/Webshop.js')
          ]
        ],
        attributes: {
            async: true
        }
    }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      // filename: "[name].css",
      // chunkFilename: "[id].css"
      filename: path.resolve(htmlOutputPath, 'Resources/bundle.css'),
      publicPath: path.resolve(__dirname, '../../html/images')
    }),
    new WriteFilePlugin()
  ],
  externals: {
    Cookies: "Cookies",
  },
  devServer: {
    proxy: {
      '/Ajax': 'http://192.168.56.102',
      '/Download': 'http://192.168.56.102'
    },
    // contentBase: path.resolve(htmlOutputPath, '../app/View/Script/Page/NewWebshop'),
    contentBase: path.resolve(__dirname, '../../app/View/Script/Page/NewWebshop'),
    publicPath: "http://localhost:8080",
    filename: 'bundle.js'
  }
};

Add ability to set property to uglify or not

Currently you must have NODE_ENV='production' to uglify the code. If you have something like webpack --env=prod it will ignore that.

Example:

new ConcatPlugin({
    uglify: true
})

Please Add a License

Hello, I would like to use this but I need a License on this project todo so.

Thank you

Webpack 4

Any plans to support webpack 4 soon?

Thanks

Cannot read property 'length' of undefined.

Hello,

I'm trying to build a angular4 course work, however the build fails at 95% pointing to line 123 of your plugin.
95% emittingUnhandled rejection TypeError: Cannot read property 'length' of undefined at Object.size (C:\Users\Cliente\Downloads\themeforest-20161805-egret-angular-4-material-design-admin-templa te\Egret-Angular-Material-admin\Seed-project\node_modules\webpack-concat-plugin\index.js:128:39) at obj.assets.compilationAssets.map.asset (C:\Users\Cliente\Downloads\themeforest-20161805-egret-angular-4-m aterial-design-admin-template\Egret-Angular-Material-admin\Seed-project\node_modules\webpack\lib\Stats.js:258:38 )

Have you seen this? Any help would be greatly appreciated.

Allow passing on Uglify options

This is a feature request.

Currently the uglify option is only true/false, but it would be nice to be able to pass on a few more options.

I'd like to work on this feature if you accept the idea.

Generate Source Map with sourcesContent

Hi,
in my case the sources of the concated files are outside the webroot. this causes that i can not follow the source file along in chrome when debugging. So afaik for this case, the source maps support the sourcesContent option (i found this https://stackoverflow.com/a/19803425)

currently i have

devtool: 'source-map'

and

new ConcatPlugin({
uglify: false,
sourceMap: true,
...

Can someone please give me a hint / what to do?
I am not shure how webpack-concat-plugin handles source map, so is it influences by devtools setting for other webpack source map plugins?

filesToConcat - avoid direct list of files

Hi, there.
Can i just use instead of :

filesToConcat: [
   '/path/to/file1.js',
   '/path/to/file2.js',
   '/path/to/file3.js',
]

something like that:

filesToConcat: {
   recursive: true,
   path: '/path/to/*.js'
}

Using 'uglify: true' breaks the output for IE 11

When uglify: true, output is transformed in the way, which produces runtime errors in IE 11.

For example, undefined check:

typeof varName1 !== "undefined"

is transformed to:

0 !== varName1 

which fails with "Wrong number of arguments or invalid property assignment" error at runtime.

Most likely, related to the mishoo/UglifyJS#2813

Inline source map

Would be nice if this were possible. Also, if it could implicitly rely on devtool.

Ability to prevent leaking of globals from the concatenation

Feature suggestion:

Currently the files are simply concatenated. It would be nice to have an option to concat multiple files, but then lock them all in some kind of scope.

Even better, if it could work together then with something like expose-loader.

How to inject script name into specific chunk or file?

Is there a way to tell the concat plugin into which chunk or html file to inject the script it generates?

I have a webpack config with multiple entries, each of which results in a separate emitted html file.
I use the concat-plugin to build separate vendor scripts for each of the entries. The problem I am having is that each of the emitted html files is injected with all of the vendor scripts.

So, the config consists of this:

entry: {
    client:      'index.js',
    user:        'index-user.js',
 }

And the concat plugins are configured like this

// For index.js
new ConcatPlugin({
    name:          'vendor-js',
    fileName:      '[name].[hash:8].js',
    filesToConcat: [ vendor_files.js ],
}),

// For index-user.js
new ConcatPlugin({
    name:          'vendor-user-js',
    fileName:      '[name].[hash:8].js',
    filesToConcat: [ vendor_files.jsUser ],
}),

Currently, there are two index.html files generated, index.html and index-user.html, both of which include both concatenated scripts, like so:

    <script type="text/javascript" src="/vendor-js.c8e444ce.js"></script>
    <script type="text/javascript" src="/vendor-user-js.c9e464ce.js"></script>

I need index.html to only include

    <script type="text/javascript" src="/vendor-js.c8e444ce.js"></script>

and index-user.htlm to include this

    <script type="text/javascript" src="/vendor-user-js.c9e464ce.js"></script>

Thanks.

[Question] - watch mode with concat plugin

Hi,

I have configuration which works good without watch mode, but with watch mode it runs in infinity loop and I want to confirm is it expected behaviour.

I'm using:

"webpack": "^4.16.3",
"webpack-cli": "^3.1.0",
"webpack-concat-plugin": "^3.0.0"

Scenario:

{
    entry: {
        "js/webpack/dummyEntryOutput": "./js/webpack/dummyEntry.js"
    },
    watch: true,
    output: {
        path: path.resolve(__dirname, "")
    },
    plugins: [
        new ConcatPlugin(
            {
                fileName: "/js/bootstrap/bootstrap.js", // create file which will be used later
                filesToConcat: [
                    "./js/bootstrap/file1.js",
                    "./js/bootstrap/file2.js"
                ]
            }
        ),
        new ConcatPlugin(
            {
                fileName: "/js/widgets/widgetsConnect.js",
                filesToConcat: [
                    "./js/jquery.js",
                    "./js/bootstrap/bootstrap.js" // reusing file created above
                ]
            }
        )
    ]
}

As you can see in configuration I'm reusing file which was created before. When I'm running this config it runs in infinity loop even if I didn't make any changes on any file. I expected to run this once (when no change is made).

Any ideas why is that? Is it possible to prevent infinity loop and achieve the same result?

PS: I know that this is specific scenario, but unfortunately I need to force it to run that in that form (this is old legacy system with tons of dependencies).

Thanks
Rafal

DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead

I got the error message below
DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead

I have updated the node.js to 10.15.3.
Here is my package.json file
"dependencies": {
"glob": "^7.1.3",
"lodash": "^4.17.11"
},
"devDependencies": {
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"babel-loader": "^8.0.5",
"babel-plugin-lodash": "^3.3.4",
"css-loader": "^2.1.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"lodash-webpack-plugin": "^0.11.5",
"node-sass": "^4.11.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"uglifyjs-webpack-plugin": "^2.1.2",
"webpack": "^4.11.0",
"webpack-cli": "^3.2.3",
"webpack-concat-plugin": "^3.0.0",
"webpack-merge-and-include-globally": "^2.1.16",
"webpack-sweet-entry": "^1.1.9"
},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"repository": {
"type": "git"
},
"keywords": [],
"license": "ISC"
}

Here is the contatPlugin configuration in webpack.config.js
new ConcatPlugin({
uglify: false,
sourceMap: false,
name: 'js',
outputPath: path.resolve(__dirname, 'main/webapp/asset/'),
fileName: '[name].js',
filesToConcat: [path.resolve(sourcePath, 'js/**/*.js')],
attributes: {
async: true
}
}),

the path separator in window os

Windows OS, the webpack.conf.js:

new ConcatPlugin({
      ...
      "name": "scripts",
      "fileName": 'js/[name].bundle.js',
      ...
    }),

when insert into html, htmlWebpackPlugin.files.webpackConcat.scripts is js\scripts.bundle.js, instead of js/scripts.bundle.js

Upgrade to html-webpack-plugin 4

The html-webpack-plugin version 4 is getting closer to a release.
Many information can be found in this pr: jantimon/html-webpack-plugin#953

A static version property was added:
https://github.com/jantimon/html-webpack-plugin/blob/d65b37d2c588047e0d81a38f4645fcdb3ead0b9e/index.js#L915-L927

The event system was changed alot to work with the new features:

Could you please give the new events a try and let me know if they work for your case?
https://github.com/jantimon/html-webpack-plugin/tree/webpack-4#events

beforeAssetTagGeneration hook

    AsyncSeriesWaterfallHook<{
      assets: {
        publicPath: string,
        js: Array<{string}>,
        css: Array<{string}>,
        favicon?: string | undefined,
        manifest?: string | undefined
      },
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTags hook

    AsyncSeriesWaterfallHook<{
      assetTags: {
        scripts: Array<HtmlTagObject>,
        styles: Array<HtmlTagObject>,
        meta: Array<HtmlTagObject>,
      },
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTagGroups hook

    AsyncSeriesWaterfallHook<{
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

afterTemplateExecution hook

    AsyncSeriesWaterfallHook<{
      html: string,
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

beforeEmit hook

    AsyncSeriesWaterfallHook<{
      html: string,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

afterEmit hook

    AsyncSeriesWaterfallHook<{
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

Source map wrong location

Something is off with source map as I just got en error pointing to a certain row in both chrome and firefox which was completely off.

When I removed the file in error from the concatanation and manually including the full file in the project did I get a completely different line (the correct line).

Let me know if anyone wants to track this down, I will be happy to assist.

Support devserver

It will be nice if this plugin can support webpack devserver watch.

Going up a directory for files in the filesToConcat option

I am trying to use webpack-concat-plugin to concat files that live under the current directory where webpack.config.js lives, and also files that live under a different directory accessed from the current directory's parent, like this:

    new ConcatPlugin({
      uglify: false,
      sourceMap: true,
      name: 'ang1_app',
      fileName: '[name].js',
      filesToConcat: ['./client/**/*.js', '../other_dir/client/**/*.js'],
      attributes: {
        async: true
      }
    }),

However, the filesToConcat option does not seem to know how to travel up the directory tree and does not include anything from the second glob (if I move "other_dir" under the current directory, it correctly finds and concats the files). Any advice on how to handle this case without having to move the other directory (which contains files shared by our other apps)?

Thanks!

No entry points

Hi. Thank you for create this plugin.
I was trying to use webpack just for minify and concat some files.

Now I have the next:

var path = require('path');
const ConcatPlugin = require('webpack-concat-plugin');

module.exports = {
  // src folder is excluded from jekyll’s build process
  // we’re going to put the generated files in the js folder, and jekyll will grab it
  entry: [],
  output: {
    path: path.resolve(__dirname, 'js')
  },
  plugins: [
    new ConcatPlugin({
      uglify: true, // uglify js or set process.env.NODE_ENV = 'production'
      fileName: 'init.js',
      filesToConcat: ['./src/doubletaptogo.js', './src/init.js']
    }),
    new ConcatPlugin({
      uglify: true, // uglify js or set process.env.NODE_ENV = 'production'
      fileName: 'skills-stick.js',
      filesToConcat: ['./src/skills-stick.js']
    })
  ],

  module: {
  loaders: [
    {
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ['es2015']
      }
    }
    ]
  }
};

I want to use the plugin twice.
At least for now I don't have files with dependencies, for that reason I have an empty entry.
But webpack fails. Do you know how I can avoid that error?

Thank you.

Add option to cache/skip older files

Currently, files are concatenated on every build. It would be nice to have an option to either cache the files based on their content (calculating hashes of the file contents and comparing the hashes to the last known output). Alternatively, it could compare the modification dates to the output file and skip concatenating if the output file is newer.

contenthash does not work. hash changes every time

webpack's [contenthash] functionality doesn't work in this plugin. And the provided hash functionality generates a different hash everytime. This is not good for caching. Am I doing something wrong? Or is this how it is?

compiler.hooks not defined. Running with webpack 1.15.0

Does this plugin work with webpack 1.x ? I've a legacy project with webpack 1.15.0 and when I tried using the plugin to concatenate a bunch of legacy js files ( having globals all around, without any module system ), this error was thrown.

 /Users/arihant.verma/Documents/code/fore/node_modules/webpack-concat-plugin/release.js:346
[0]             compiler.hooks.compilation.tap('webpackConcatPlugin', function (compilation) {
[0]                            ^
[0]
[0] TypeError: Cannot read property 'compilation' of undefined

Concat and import

Hie!

I want first to concat my old js files into one file and then import this new file to my main app.js.
I can't import each file separately since they have to use functions from each other and webpack isolates them and prevents it.

Webpack-concat-plugin creates file, but it can't be imported.

My config:

const path = require('path');
const autoprefixer = require('autoprefixer');
const plugins = require('./webpack/plugins');
const includesLoader = require('./webpack/includesLoader');

const SRC_DIR = path.resolve(__dirname, 'resources/assets/src');
const DIST_DIR = path.resolve(__dirname, 'public/dist');

const svgObject = require('./webpack/svgObject')(SRC_DIR + '/svg');

let config = (env, argv) => {
    let isProd = argv.mode === 'production';

    return {
        entry: SRC_DIR + '/js/app.js',
        output: {
            path: DIST_DIR,
            filename: 'js/bundle.js'
        },

        resolveLoader: {
            modules: ['node_modules', './webpack/']
        },

        resolve: {
            modules: [
                "node_modules",
                "resources/assets/src/spritesmith-generated",
                "resources/assets/src/img",
                "resources/assets/src/legacy/img",
                "resources/assets/src/fonts"
            ]
        },

        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: SRC_DIR,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015']
                    }
                },
                {
                    test: /\.(scss|css)$/,
                    use: [
                        {
                            loader: "file-loader",
                            options: {
                                name: 'css/style.css'
                            }
                        },
                        {
                            loader: 'extract-loader',
                            options: {
                                publicPath: '../'
                            }
                        },
                        {
                            loader: "css-loader",
                            options: {
                                minimize: isProd,
                                alias: {
                                    "../fonts/roboto": path.resolve(__dirname, "node_modules/materialize-css/dist/fonts/roboto")
                                }
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function () {
                                    return [autoprefixer('last 2 versions', 'ie 10')]
                                }
                            }
                        },
                        "sass-loader"
                    ]
                },
                {
                    test: /\.pug$/,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: '[name].html'
                            }
                        },
                        {
                            loader: 'pug-html-loader',
                            options: {
                                pretty: true,
                                data: {
                                    svg: svgObject
                                }
                            }
                        },
                        {
                            loader: 'includesLoader',
                            options: {
                                pathToIncludes: SRC_DIR + '/includes'
                            }
                        }
                    ]
                },
                {
                    test: /\.png$/,
                    include: [ SRC_DIR + '/spritesmith-generated' ],
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'img/sprite/[name].png'
                            }
                        }
                    ]

                },
                {
                    test: /\.(jpe?g|png|gif|svg)$/i,
                    include: [ SRC_DIR + '/img', SRC_DIR + '/legacy/img' ],
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'img/[name].[ext]'
                            }
                        }
                    ]

                },
                {
                    test: /\.(eot|svg|ttf|woff|woff2)$/i,
                    include: [ SRC_DIR + '/fonts', path.resolve(__dirname, 'node_modules/materialize-css/dist/fonts/roboto') ],
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'fonts/[name].[ext]'
                            }
                        }
                    ]

                }
            ]
        },

        plugins: plugins(isProd, SRC_DIR, DIST_DIR),

        devServer: {
            disableHostCheck: true,
            host: '0.0.0.0'
        }
    }
};

module.exports = config;

plugins:

const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const SpritesmithPlugin = require('webpack-spritesmith');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const ConcatPlugin = require('webpack-concat-plugin');

let plugins = (isProd, src, dist) => {
    let SRC_DIR = src;
    let DIST_DIR = dist;

    //common for dev and prod plugins
    let pluginsArr = [
        new ConcatPlugin({
            filesToConcat: [ './resources/assets/src/legacy/js/partials/*' ],
            // outputPath: SRC_DIR,
            fileName: 'legacy.bundle.js',
            injectType: 'none'
        }),

        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),

        new CopyWebpackPlugin([
            {
                from: SRC_DIR + '/img/',
                to: DIST_DIR + '/img/'
            },
            {
                from: SRC_DIR + '/legacy/img/',
                to: DIST_DIR + '/img/'
            },
            {
                from: SRC_DIR + '/legacy/admin-extras/css/',
                to: DIST_DIR + '/css/'
            },
            {
                from: SRC_DIR + '/fonts/',
                to: DIST_DIR + '/fonts/',
            },
            {
                from: SRC_DIR + '/legacy/admin-extras/js/',
                to: DIST_DIR + '/js/',
            }
        ]),
        new ImageminPlugin({
            test: /\.(jpe?g|png|gif|svg)$/i,
            disable: !isProd,
            optipng: {
                optimizationLevel: 3
            }

        })
    ];

    //3 sprites: 1x, 2x, 3x
    for(let i = 1; i < 4; i++) {
        pluginsArr.push(
            new SpritesmithPlugin({
                src: {
                    cwd: path.resolve(__dirname, `../src/sprite/${i}x`),
                    glob: '*.png'
                },
                target: {
                    image: SRC_DIR + `/spritesmith-generated/sprite${i}x.png`,
                    css: SRC_DIR + `/src/scss/components/sprite/_sprite${i}x.scss`
                },
                apiOptions: {
                    cssImageRef: `~sprite${i}x.png`
                    // cssImageRef: `../img/sprite/sprite${i}x.png`
                }
            })
        );
    }

    return pluginsArr;
};

module.exports = plugins;

app.js:

import './../index.pug';
import './../pages/main.pug';

import './../scss/style.scss';

import Sandwich from './components/sandwich';
import Accordion from './components/accordion';
import Question from './components/question';

//LEGACY
import 'imports-loader?define=>false!./legacy.bundle.js';
//-LEGACY

//NEW
new Sandwich('.js-sandwich', '.js-sandwich-menu').init();
new Accordion().init();
new Question().init();

Don't log outputPath

It's not consistent with the rest of the webpack log:

                      Asset      Size          Chunks             Chunk Names
/project/build/legacyApp.js  4.11 MiB                  [emitted]  
                  ccApp.css  26.3 KiB           ccApp  [emitted]  ccApp
                   ccApp.js   117 KiB           ccApp  [emitted]  ccApp
         ccDesignSystem.css  60.6 KiB  ccDesignSystem  [emitted]  ccDesignSystem
          ccDesignSystem.js  1.63 MiB  ccDesignSystem  [emitted]  ccDesignSystem
                 ccUser.css    27 KiB          ccUser  [emitted]  ccUser
                  ccUser.js  50.1 KiB          ccUser  [emitted]  ccUser
                 common.css   678 KiB          common  [emitted]  common
                  common.js  11.7 MiB          common  [emitted]  common

Concatenated output is not emitted to html file after upgrade

I am using [email protected], [email protected] and [email protected]. I have two instances of the plugin concatenating different sets of js files. After upgrading to webpack 4 and respective 3.0.0 version, the plugin is building the assets but not injecting the script tags into the html document. Here is my config:

config.plugins = [
    new WebpackPluginConcat({       
        filesToConcat: appConfig.externals,
        name: 'externals'
    }),
    new WebpackPluginConcat({
        filesToConcat: appConfig.vendor,
        name: 'vendor'
    }),
    new WebpackPluginHtml({
        favicon: './src/img/favicon.ico',
        template: './src/index.html'
    }),
];

And the output html file:

<html>
    <head>
        <meta charset="UTF-8">
        <title>My Application</title>
    </head>
    <body>
        <main id="content"></main>
        <!-- Nothing inserted here after the upgrade -->
        <script src="bundle.js">
    </body>
</html>

Although I have files in the output directory:

+ public/
|
+-- bundle.js
+-- externals.js
+-- index.html
+-- vendor.js

The Changelog doesn't mention anything about migration after the upgrade. Am I missing something?

One thing I noticed was this warning from #68 and #73 in the log when building. Is there a mismatch may be between the html-webpack-plugin and this module?

When in watch mode emits on any dependency change.

Currently each time webpack runs due to a dependency change this plug-in reemits files even if the files it cares about haven't changed. It would be ideal to only emit on the first run, then only emit if a file passed into the plug-in changes.

I've worked out the bits to do this, save for cleaning somethings up. Would you be interested in a PR for this?

Remove process.env.NODE_ENV

Hello, I want to say thank you so much for this plugin. But I have problem with it. process.env.NODE_ENV === 'production' is excessive and minify the bundle on production when you don't need it. Can you remove it? self.settings.uglify is sufficient check. Also [hash] don't respond for shortened version like [hash:8]. Can you fix it, please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.