GithubHelp home page GithubHelp logo

ztoben / assets-webpack-plugin Goto Github PK

View Code? Open in Web Editor NEW
963.0 963.0 110.0 635 KB

Webpack plugin that emits a json file with assets paths

Home Page: https://www.npmjs.com/package/assets-webpack-plugin

License: MIT License

JavaScript 100.00%

assets-webpack-plugin's Introduction

assets-webpack-plugin

version downloads License: MIT Build Status Build status

Webpack plugin that emits a json file with assets paths.

Table of Contents

Install

โš ๏ธ Starting with version 6, this plugin works with Webpack 5+.

If you are working with an older version of Webpack, you can use the most recent 5.x.x release (5.1.2).

npm install assets-webpack-plugin --save-dev

If you're using Webpack 4 or below:

npm install [email protected] --save-dev

Why Is This Useful?

When working with Webpack you might want to generate your bundles with a generated hash in them (for cache busting).

This plug-in outputs a json file with the paths of the generated assets so you can find them from somewhere else.

Example output:

The output is a JSON object in the form:

{
    "bundle_name": {
        "asset_kind": "/public/path/to/asset"
    }
}

Where:

  • "bundle_name" is the name of the bundle (the key of the entry object in your webpack config, or "main" if your entry is an array).
  • "asset_kind" is the camel-cased file extension of the asset

For example, given the following webpack config:

{
    entry: {
        one: ['src/one.js'],
        two: ['src/two.js']
    },
    output: {
        path: path.join(__dirname, "public", "js"),
        publicPath: "/js/",
        filename: '[name]_[hash].bundle.js'
    }
}

The plugin will output the following json file:

{
    "one": {
        "js": "/js/one_2bb80372ebe8047a68d4.bundle.js"
    },
    "two": {
        "js": "/js/two_2bb80372ebe8047a68d4.bundle.js"
    }
}

Configuration

In your webpack config include the plug-in. And add it to your config:

var path = require('path')
var AssetsPlugin = require('assets-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin()

module.exports = {
    // ...
    output: {
        path: path.join(__dirname, "public", "js"),
        filename: "[name]-bundle-[hash].js",
        publicPath: "/js/"
    },
    // ....
    plugins: [assetsPluginInstance]
}

Options

You can pass the following options:

filename

Optional. webpack-assets.json by default.

Name for the created json file.

new AssetsPlugin({filename: 'assets.json'})

fullPath

Optional. true by default.

If false the output will not include the full path of the generated file.

new AssetsPlugin({fullPath: false})

e.g.

/public/path/bundle.js vs bundle.js

removeFullPathAutoPrefix

Optional. false by default.

If true the full path will automatically be stripped of the /auto/ prefix generated by webpack.

new AssetsPlugin({removeFullPathAutoPrefix: true})

e.g.

/public/path/bundle.js vs bundle.js

includeManifest

Optional. false by default.

Inserts the manifest javascript as a text property in your assets. Accepts the name or names of your manifest chunk. A manifest is the last CommonChunk that only contains the webpack bootstrap code. This is useful for production use when you want to inline the manifest in your HTML skeleton for long-term caching. See issue #1315 or a blog post to learn more.

new AssetsPlugin({includeManifest: 'manifest'})
// assets.json:
// {entries: {manifest: {js: `hashed_manifest.js`, text: 'function(modules)...'}}}
//
// Your html template:
// <script>
// {assets.entries.manifest.text}
// </script>

The includeManifest option also accepts an array of manifests:

new AssetsPlugin({includeManifest: ['manifest1', 'manifest2']})
// assets.json:
// {entries: {
//    manifest1: {js: `hashed_manifest.js`, text: 'function(modules)...'},
//    manifest2: {js: `hashed_manifest.js`, text: 'function(modules)...'}
// }}

manifestFirst

Optional. false by default.

Orders the assets output so that manifest is the first entry. This is useful for cases where script tags are generated from the assets json output, and order of import is important.

new AssetsPlugin({manifestFirst: true})

path

Optional. Defaults to the current directory.

Path where to save the created JSON file. Will default to the highest level of the project unless useCompilerPath is specified.

new AssetsPlugin({path: path.join(__dirname, 'app', 'views')})

useCompilerPath

new AssetsPlugin({useCompilerPath: true})

Will override the path to use the compiler output path set in your webpack config.

prettyPrint

Optional. false by default.

Whether to format the JSON output for readability.

new AssetsPlugin({prettyPrint: true})

processOutput

Optional. Defaults is JSON stringify function.

Formats the assets output.

new AssetsPlugin({
  processOutput: function (assets) {
    return 'window.staticMap = ' + JSON.stringify(assets)
  }
})

update

Optional. false by default.

When set to true, the output JSON file will be updated instead of overwritten.

new AssetsPlugin({update: true})

metadata

Inject metadata into the output file. All values will be injected into the key "metadata".

new AssetsPlugin({metadata: {version: 123}})
// Manifest will now contain:
// {
//   metadata: {version: 123}
// }

includeAllFileTypes

Optional. true by default.

When set false, falls back to the fileTypes option array to decide which file types to include in the assets file.

new AssetsPlugin({includeAllFileTypes: false})

fileTypes

Optional. ['js', 'css'] by default.

When set and includeAllFileTypes is set false, only assets matching these types will be included in the assets file.

new AssetsPlugin({fileTypes: ['js', 'jpg']})

keepInMemory

Optional. false by default.

When set the assets file will only be generated in memory while running webpack-dev-server and not written to disk.

new AssetsPlugin({keepInMemory: true})

integrity

Optional. false by default.

When set the output from webpack-subresource-integrity is included in the assets file.

Please make sure you have webpack-subresource-integrity installed and included in your webpack plugins.

new AssetsPlugin({integrity: true})

Output will now look like this:

{
  "main": {
    "js": "/bundle.js",
    "jsIntegrity": "sha256-ANGwtktWN96nvBI/cjekdTvd0Dwf7SciIFTQ2lpTxGc= sha384-Ly439pF3K+J8hnhk1BEcjKnv1R9BApFYVIVJvr64PcgBjdT4N7hfPzQynItHwcaO"
  },
  "vendors~main": {
    "js": "/1.bundle.js",
    "jsIntegrity": "sha256-yqNi1hgeAdkXVOORgmVMeX+cbuXikoj6I8qWZjPegsA= sha384-4X75tnsGDwnwL5kBUPsx2ko9DeWy0xM8BcDQdoR185yho+OnxjjPXl2wCdebLWTG"
  }
}

entrypoints

Optional. false by default.

If the 'entrypoints' option is given, the output will be limited to the entrypoints and the chunks associated with them.

new AssetsPlugin({entrypoints: true})

includeFilesWithoutChunk

Optional. false by default.

When set and entrypoints is set true, will output any files that are part of the unnamed chunk to an additional unnamed ("") entry.

new AssetsPlugin({includeFilesWithoutChunk: true})

includeAuxiliaryAssets

Optional. false by default.

When set, will output any files that are part of the chunk and marked as auxiliary assets.

new AssetsPlugin({includeAuxiliaryAssets: true})

includeDynamicImportedAssets

Optional. false by default.

When set, will output any files that are part of the chunk and marked as preloadable or prefechtable child assets via a dynamic import. See: https://webpack.js.org/guides/code-splitting/#prefetchingpreloading-modules

new AssetsPlugin({includeDynamicImportedAssets: true})

Using in multi-compiler mode

If you use webpack multi-compiler mode and want your assets written to a single file, you must use the same instance of the plugin in the different configurations.

For example:

var webpack = require('webpack')
var AssetsPlugin = require('assets-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin()

webpack([
  {
    entry: {one: 'src/one.js'},
    output: {path: 'build', filename: 'one-bundle.js'},
    plugins: [assetsPluginInstance]
  },
  {
    entry: {two:'src/two.js'},
    output: {path: 'build', filename: 'two-bundle.js'},
    plugins: [assetsPluginInstance]
  }
])

Using this with Rails

You can use this with Rails to find the bundled Webpack assets via Sprockets. In ApplicationController you might have:

def script_for(bundle)
  path = Rails.root.join('app', 'views', 'webpack-assets.json') # This is the file generated by the plug-in
  file = File.read(path)
  json = JSON.parse(file)
  json[bundle]['js']
end

Then in the actions:

def show
  @script = script_for('clients') # this will retrieve the bundle named 'clients'
end

And finally in the views:

<div id="app">
  <script src="<%= @script %>"></script>
</div>

Using this with ASP.NET Core

You can use this with ASP.NET Core via the WebpackTag library.

Test

npm test

assets-webpack-plugin's People

Contributors

chaffeqa avatar daniel15 avatar den-dp avatar dguo avatar dimchez avatar erikt9 avatar ernestorocha avatar galkinrost avatar geldmacher avatar greenkeeper[bot] avatar hashwin avatar ibash avatar jgerigmeyer avatar kane-c avatar kossnocorp avatar kronuz avatar lencioni avatar linusu avatar mattkrick avatar monteiro avatar patrick-mcdougle avatar renovate-bot avatar rosenfeld avatar snyk-bot avatar stof avatar trainmaster avatar tuch avatar webdeveric avatar wmertens avatar ztoben 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  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

assets-webpack-plugin's Issues

Hot module reload not working

Hi

If I change a CSS file, I get the following error in the browser

process-update.js?e13e:81 [HMR] The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See http://webpack.github.io/docs/hot-module-replacement-with-webpack.html for more details.logUpdates @ process-update.js?e13e:81applyCallback @ process-update.js?e13e:49hotApply @ site_vendor.js:520cb @ process-update.js?e13e:52hotUpdateDownloaded @ site_vendor.js:300hotAddUpdateChunk @ site_vendor.js:272webpackHotUpdateCallback @ site_vendor.js:28(anonymous) @ 3.1a691a9โ€ฆ.hot-update.js:1
process-update.js?e13e:89 [HMR]  - ./src/assets.json

Plugin fails if output directory does not exist already

I'd like to write the asset-definitions to webpack's output path, so I have the folllowing configuration:

myConfig.plugins = [
    ...
    new AssetsPlugin({path: myConfig.output.path})
];

This works fine, except if the directory does not exist already since the plugin will try to write to it before webpack has created the directory.

It would be nice if the plugin would automatically mkdirp the output directory before trying to write the file.

Option "update" doesn't work.

Hello!
I'm running with different entries: webpack --env.option opt1 && webpack --env.option opt2
I expect that my output files will be updated in manifest file and this file will contain both output files from opt1 and opt2 but instead my manifest file is overwritten with output files only from opt2.
An asset plugin is initialised outside module export function ( let assetsPluginInstance = new AssetsPlugin({update: true})
Webpack v.:3.3.0

Hot module chunk is exported instead of main file

When using the plugin with hot module replacement, it seems the hot chunks are exported to the manifest instead of the main file which would then require said chunks.

Consider that this is the output of a change during a hot reload session:

                               Asset      Size  Chunks             Chunk Names
                              hot.js   1.69 MB       0  [emitted]  main
0.e5624569d7cdf05006fa.hot-update.js   5.71 kB    0, 0  [emitted]  main, main
e5624569d7cdf05006fa.hot-update.json  36 bytes          [emitted]
                             hot.css    422 kB       0  [emitted]  main

What should be in the manifest is hot.js, but instead it's 0.e5624569d7cdf05006fa.hot-update.js which, if included as asset, will just throw Uncaught ReferenceError: webpackHotUpdate is not defined and crash. Manually including hot.js makes hot reloading work as expected.

Webpack 2, fullPath option having no effect

I'm having trouble getting the fullPath option to work with my config. The JSON is generated just fine, but when adding fullPath: false there is no difference in the generated file. File paths are still the full length.

Here's what my config looks like:

new AssetsPlugin({
    filename: 'assets.json',
    fullPath: false
})

Does this plugin work with webpack 2? Thanks :)

No longer prepends publicPath to mapping.

In version 0.3.1, the publicPath was automatically prepended to the asset mapping, resulting in a full path, e.g.:

{
  "main": "/path/to/main.bundle.js"
}

With the upgrade the version 2.0.0, this seems to be missing, resulting in just the filename, e.g.:

{
  "main": {
    "js": "main.bundle.js"
  }
}

Do you have any plans to reintroduce this feature? It seems it's just commented out in the source code: https://github.com/sporto/assets-webpack-plugin/blob/master/index.js#L82-84. For dynamic builds where the publicPath is different in dev and prod environments, it's very helpful to include the full path in the asset mapping.

Thanks!

memoryFS

Is there a way to write the webpack-assets.json to memoryFS rather than disk?

or maybe just return the resulting json rather write to disk?

I have also asked this question here knowing that you are looking for help to maintain this project and may be too busy to get back with an answer any time soon.

catamphetamine/webpack-isomorphic-tools#92

Sort order of JSON assets

I'm using React server rendering to generate the HTML for a website. I'm trying to use assets-webpack-plugin so I can generate the script tags for the webpack asset bundles.

I am generating a manifest.js file using the CommonsChunkPlugin() plugin.

At the moment, the resulting JSON assets file puts the manifest.js bundle last, like this:

{
  "bundle": {
    "js": "js/bundle.js",
    "css": "css/bundle.css"
  },
  "vendor": {
    "js": "js/vendor.js"
  },
  "manifest": {
    "js": "js/manifest.js"
  }
}

I have a function to generate the HTML tags, it takes the assets from the JSON file (and uses lodash/map):

function assetTags (assets, type) {
  const tags = map(assets, (asset, index) => {
    return <script key={index} src={asset[type]} />
  })
  return tags
}

This produces:

<script src="js/bundle.js"></script>
<script src="js/vendor.js"></script>
<script src="js/manifest.js"></script>

I need the manifest to be first to avoid errors.

I know I can update my assetTags() function to do this manually, but it would be nice to have an option for sorting the bundles in the output JSON file. Or, an option like manifestFirst: true because it's always going to need to be added first in the HTML.

Have webpack-assets.json persist

Is there anyway that I can have the json file persist instead of it always being newly generated when I run a new instance of your plugin?

My use case is for using webpack dl. I first create the file and save the vendor asset when I run the dll webpack config. But I want the json file to persist (not get overwritten) when I run my webpack middleware config.

Anyway about doing this?

multiple css files not written to json file

i'm using extract-text-webpack-plugin to extract 2 css files. assets-webpack-plugin is unfortunately only writing a reference to one of these files in the json. here's the relevant parts of my webpack config...

const extractSass = new ExtractTextPlugin({
    filename: 'styles.[contenthash].css'
});
const extractSassGlobal = new ExtractTextPlugin({
    filename: 'styles-global.[contenthash].css'
});

then inside rules...

                test: /\.scss$/,
                use: extractSass.extract({
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                modules: true,
                                localIdentName: '[name]__[local]--[hash:base64:5]'
                            }
                        },
                        {
                            loader: 'sass-loader'
                        }]
                }),
                exclude: [
                    path.resolve(__dirname, './lib/global.scss')
                ]
            },
            {
                test: /global.scss$/,
                use: extractSassGlobal.extract({
                    use: [
                        {
                            loader: 'css-loader'
                        },
                        {
                            loader: 'sass-loader'
                        }
                    ]
                })
            }

and in the plugins array...

plugins: [
        extractSass,
        extractSassGlobal,
        new AssetsPlugin({
            prettyPrint: true
        })
]

finally the generated webpack-assets.json with just the one css file reference (it's always the latter of the two specified in the plugins array)

{
"app": {
    "js": "app.01423a1f392048ff387e.js",
    "css": "styles-global.450ffe3acbcdb163cd1ee9adfbf0161d.css"
  }
}

am i doing something wrong or is this functionality not supported?

Add support for Subresource Integrity

Maybe we can add integrity information to final assets when webpack-subresource-integrity plugin is configured? For example:

{
    "one": {
        "js": "/js/one_2bb80372ebe8047a68d4.bundle.js",
        "jsIntegrity": "sha256-gbZMWbP1x0a08t/M2/63KpSdL0vGPgExy4Hag678QxQ="
    },
    "two": {
        "js": "/js/two_2bb80372ebe8047a68d4.bundle.js",
        "jsIntegrity": "sha256-gbZMWbP1x0a08t/M2/63KpSdL0vGPgExy4Hag678QxQ="
    }
}

Broken output (error in mkdirp() of createOutputWriter.js)

As of version 3.6.1 there is an error thrown when using this plugin in a webpack configuration running a gulp task with the help of webpack-stream. Here some information about my setup:

// package.json
"assets-webpack-plugin": "3.6.1",
"gulp": "4.0.0",
"webpack": "4.12.0",
"webpack-cli": "3.0.6",
"webpack-merge": "4.1.3",
"webpack-stream": "4.0.3",
// and some more packages ...
// gulpfile.js
const gulp = require('gulp');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const webpackDevConfig = require('./webpack.dev.config');
const webpackProdConfig = require('./webpack.prod.config');

// some different code ...

gulp.task('bundle', () => {
  const webpackConfig = isProduction ? webpackProdConfig : webpackDevConfig;
  return gulp.src('./frontend/app.js')
    .pipe(webpackStream(webpackConfig, webpack))
    .pipe(gulp.dest(options.targetFolder));
});

And here the error:

Error in plugin "webpack-stream"
Message:
    invalid argument
Details:
    domain: [object Object]
    domainThrown: true

The error isn't helpful at all, so I started debugging. First I enabled the showStack flag in /node_modules/plugin-error/index.js. After that, the following stack trace is displayed:

Error
    at /home/xxx/node_modules/webpack-stream/index.js:146:32
    at finalCallback (/home/xxx/node_modules/webpack/lib/Compiler.js:157:39)
    at hooks.done.callAsync.err (/home/xxx/node_modules/webpack/lib/Compiler.js:206:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/xxx/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/home/xxx/node_modules/webpack/node_modules/tapable/lib/Hook.js:35:21)
    at emitRecords.err (/home/xxx/node_modules/webpack/lib/Compiler.js:204:22)
    at Compiler.emitRecords (/home/xxx/node_modules/webpack/lib/Compiler.js:319:39)
    at emitAssets.err (/home/xxx/node_modules/webpack/lib/Compiler.js:198:10)
    at hooks.afterEmit.callAsync.err (/home/xxx/node_modules/webpack/lib/Compiler.js:305:14)
    at _err1 (eval at create (/home/xxx/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:16:1)
    at /home/xxx/node_modules/webpack-stream/index.js:192:9
    at _err0 (eval at create (/home/xxx/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:12:1)
    at /home/xxx/node_modules/assets-webpack-plugin/index.js:125:9
    at /home/xxx/node_modules/assets-webpack-plugin/lib/output/createQueuedWriter.js:14:7
    at /home/xxx/node_modules/assets-webpack-plugin/lib/output/createOutputWriter.js:19:16
    at Immediate._onImmediate (/home/xxx/node_modules/memory-fs/lib/MemoryFileSystem.js:282:5)

Then I stumbled upon #90. Those changes were introduced with 3.6.1. So I tried the previous version 3.6.0 which worked without throwing an error.

In a next step I thought it would be useful to get some information about the data around the mkdirp() call. I added the following lines lib/output/createOutputWriter.js.

mkdirp(options.path, function (err) {
  console.log('options', options);
  console.log('fs', fs);
  console.log('err', err);
  // ...

Using version 3.6.0 the following is displayed afterwards:

options { path: '.',
  filename: 'webpack-assets.json',
  prettyPrint: false,
  update: false,
  fullPath: true,
  processOutput: [Function] }
fs { constants: 
   { O_RDONLY: 0,
     O_WRONLY: 1,
     O_RDWR: 2,
     S_IFMT: 61440,
     S_IFREG: 32768,
     S_IFDIR: 16384,
     S_IFCHR: 8192,
     S_IFBLK: 24576,
     S_IFIFO: 4096,
     S_IFLNK: 40960,
     S_IFSOCK: 49152,
     O_CREAT: 64,
     O_EXCL: 128,
     O_NOCTTY: 256,
     O_TRUNC: 512,
     O_APPEND: 1024,
     O_DIRECTORY: 65536,
     O_NOATIME: 262144,
     O_NOFOLLOW: 131072,
     O_SYNC: 1052672,
     O_DSYNC: 4096,
     O_DIRECT: 16384,
     O_NONBLOCK: 2048,
     S_IRWXU: 448,
     S_IRUSR: 256,
     S_IWUSR: 128,
     S_IXUSR: 64,
     S_IRWXG: 56,
     S_IRGRP: 32,
     S_IWGRP: 16,
     S_IXGRP: 8,
     S_IRWXO: 7,
     S_IROTH: 4,
     S_IWOTH: 2,
     S_IXOTH: 1,
     F_OK: 0,
     R_OK: 4,
     W_OK: 2,
     X_OK: 1,
     UV_FS_COPYFILE_EXCL: 1,
     COPYFILE_EXCL: 1 },
  Stats: [Function: Stats],
  F_OK: 0,
  R_OK: 4,
  W_OK: 2,
  X_OK: 1,
  access: [Function],
  accessSync: [Function],
  exists: [Function],
  existsSync: [Function],
  readFile: [Function],
  readFileSync: [Function],
  close: [Function],
  closeSync: [Function],
  open: [Function],
  openSync: [Function],
  read: [Function],
  readSync: [Function],
  write: [Function],
  writeSync: [Function],
  rename: [Function],
  renameSync: [Function],
  truncate: [Function],
  truncateSync: [Function],
  ftruncate: [Function],
  ftruncateSync: [Function],
  rmdir: [Function],
  rmdirSync: [Function],
  fdatasync: [Function],
  fdatasyncSync: [Function],
  fsync: [Function],
  fsyncSync: [Function],
  mkdir: [Function],
  mkdirSync: [Function],
  readdir: [Function],
  readdirSync: [Function],
  fstat: [Function],
  lstat: [Function],
  stat: [Function],
  fstatSync: [Function],
  lstatSync: [Function],
  statSync: [Function],
  readlink: [Function],
  readlinkSync: [Function],
  symlink: [Function],
  symlinkSync: [Function],
  link: [Function],
  linkSync: [Function],
  unlink: [Function],
  unlinkSync: [Function],
  fchmod: [Function],
  fchmodSync: [Function],
  chmod: [Function],
  chmodSync: [Function],
  fchown: [Function],
  fchownSync: [Function],
  chown: [Function],
  chownSync: [Function],
  _toUnixTimestamp: [Function: toUnixTimestamp],
  utimes: [Function],
  utimesSync: [Function],
  futimes: [Function],
  futimesSync: [Function],
  writeFile: [Function],
  writeFileSync: [Function],
  appendFile: [Function],
  appendFileSync: [Function],
  watch: [Function],
  watchFile: [Function],
  unwatchFile: [Function],
  realpathSync: [Function: realpathSync],
  realpath: [Function: realpath],
  mkdtemp: [Function],
  mkdtempSync: [Function],
  copyFile: [Function],
  copyFileSync: [Function],
  createReadStream: [Function],
  ReadStream: 
   { [Function: ReadStream]
     super_: 
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Object],
        _fromList: [Function: fromList] } },
  FileReadStream: 
   { [Function: ReadStream]
     super_: 
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Object],
        _fromList: [Function: fromList] } },
  createWriteStream: [Function],
  WriteStream: 
   { [Function: WriteStream]
     super_: { [Function: Writable] WritableState: [Function: WritableState], super_: [Object] } },
  FileWriteStream: 
   { [Function: WriteStream]
     super_: { [Function: Writable] WritableState: [Function: WritableState], super_: [Object] } } }
err null

But using version 3.6.1 the output is different:

options { path: '.',
  filename: 'webpack-assets.json',
  prettyPrint: false,
  update: false,
  fullPath: true,
  processOutput: [Function] }
fs MemoryFileSystem { data: { home: { '': true, 'xxx': [Object] } } }
err { Error: invalid argument
    at pathToArray (/home/xxx/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (/home/xxx/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/home/xxx/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at writeOutput (/home/xxx/node_modules/assets-webpack-plugin/lib/output/createOutputWriter.js:17:8)
    at AssetsWebpackPlugin.queuedWriter [as writer] (/home/xxx/node_modules/assets-webpack-plugin/lib/output/createQueuedWriter.js:29:7)
    at afterEmit (/home/xxx/node_modules/assets-webpack-plugin/index.js:121:12)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/xxx/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:7:1)
    at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/home/xxx/node_modules/webpack/node_modules/tapable/lib/Hook.js:35:21)
    at asyncLib.forEach.err (/home/xxx/node_modules/webpack/lib/Compiler.js:302:27)
    at done (/home/xxx/node_modules/neo-async/async.js:2809:11)
    at /home/xxx/node_modules/neo-async/async.js:2760:7
    at MemoryFileSystem.writeFile (/home/xxx/node_modules/memory-fs/lib/MemoryFileSystem.js:328:9)
    at writeOut (/home/xxx/node_modules/webpack/lib/Compiler.js:286:29)
    at asyncLib.forEach (/home/xxx/node_modules/webpack/lib/Compiler.js:296:7)
    at baseEach (/home/xxx/node_modules/neo-async/async.js:2371:9)
    at Object.each (/home/xxx/node_modules/neo-async/async.js:2798:9)
  code: 'EINVAL',
  errno: 18,
  message: 'invalid argument',
  path: '.' }

So do you have any idea how to fix this?

Is it possible to have the same hash if file not changed ?

I tried to run the build twice. Even the file has not changed, the hash is different everytime.

Is it possible the hash is based on generated content?

One of the use cases is we can save all the version in CDN, and roll back to previous verSion if something wrong.

"[name].js?[hash]" file name not handled correctly in v2

My Webpack config has something like this in it:

  entry: {
    desktop: './js/desktop.js',
    mobile: './js/mobile.js'
  },
  output: {
    path: path.join(__dirname, 'public', 'assets', 'cache'),
    filename: process.env.NODE_ENV === 'production'
      ? '[name].min.js?[hash]'
      : '[name].js?[hash]',
  },

Output from 0.3.1:

{"desktop":"desktop.js?177b0e49e38f148eb91a","mobile":"mobile.js?177b0e49e38f148eb91a"}

This is easy, I just read the desktop property

Output from 2.2.0:

{"desktop":{"js?177b0e49e38f148eb91a":"desktop.js?177b0e49e38f148eb91a","jsMap":"desktop.js.map?177b0e49e38f148eb91a"},"mobile":{"js?177b0e49e38f148eb91a":"mobile.js?177b0e49e38f148eb91a","jsMap":"mobile.js.map?177b0e49e38f148eb91a"}}

What do I do here? The key has the hash in it :/ I could do the equivalent of Object.keys(assets.desktop)[0] but that's a bit ugly.

I've reverted to 0.3.1 in the meantime.

splitted files not found when used with AggressiveSplittingPlugin

using this configuration:

new AssetsPlugin({
                filename: "assets." + lang + ".json",
                fullPath: false
            }),

produces the correct output for the entry look-up

however, once AggressiveSplittingPlugin is added:

new AssetsPlugin({
                filename: "assets." + lang + ".json",
                fullPath: false
            }),
new webpack.optimize.AggressiveSplittingPlugin({
                minSize: 30000,
                maxSize: 50000
            }),

produces the incorrect output.

expected:

  • output file should show the list of chunks or entry chunk for the splitted files

findings:

  • very small entry bundles not affected by the splitting plug-in would still show up in the output file
  • large bundles that have been splitted into smaller chunks do not show up

Env:
node v8.0.0
assets-webpack-plugin: 3.5.1
webpack: 3.0.0-rc.0

No assets in manifest with `copy-webpack-plugin`

If i use copy-webpack-plugin

new CopyWebpackPlugin([
                {
                    from: DEBUG
                        ? path.join(process.cwd(), 'node_modules/jquery/dist/jquery.js')
                        : path.join(process.cwd(), 'node_modules/jquery/dist/jquery.min.js'),
                    to: 'jquery/jquery.js' // use 'jquery/jquery.[hash].js' also not working
                }
]);

I do not have jquery in the assets manifest, is there something you can solve it or a bug?

Support multiple asset types per chunk

Hello!

Seems like this only supports one asset type per chunk. Stuff breaks when I have multiple css per chunk. For e.g.

index.css
index.above.css

It outputs something like this

  "index": {
    "js": "/mobile/public/dist/index.eae6d77f.js",
    "css": "/mobile/public/dist/index.3dcf8c31.above.css"
  },

I could send in a PR if we could agree on how to handle these cases.

Incompatible with inline source maps

If I use inline source maps I get error: Could not locate manifest function in source.

Error occurs in node_modules/assets-webpack-plugin/index.js
This occurs because compilation.assets[manifestAssetKey] contains children field (array) instead of _value field while inline source map used.

License Clarification

Hey Sasha,
Can you clarify the license for me? The package.json lists MIT in the SPDX ID, but I can't track down the license terms anywhere in the repo. Can you add a license.text file with the license terms?

Thanks,
Brian

Can this works with other files than entries?

Hi,

It is longtime, when i started to fight with simple idea where i want to export all relevant files into hash like your package does. Not just main javascripts, but stylesheets and all other assets (images, fonts etc...) required by webpack.
Stats result is really huge and contains all files which are required in my app and are hard to works with.

Maybe you can do something like that with you module, but you just skip that because you dont need it, or have major know-how about stat file and how this can be dome?

Thanks

Incorrect concatination of asset file names and directory path

Issue description

Hi, I tried this plugin and my publicPath and my chunk names are concatenated without a slash in between:

publicPath: "/assets",
assetsByChunkName: {
  main: [
    'app-c72b8e3607a4176d7a01.js',
    'app-c72b8e3607a4176d7a01.js.map'
  ],
  vendor: [
    'vendor-ffe9523a5337969b51e2.js',
    'vendor-ffe9523a5337969b51e2.js.map'
  ]
}

And the resulting JSON file looks like this:

{"main":{"js":"/assetsapp-c72b8e3607a4176d7a01.js"},"vendor":{"js":"/assetsvendor-ffe9523a5337969b51e2.js"}}

In think the problem is this line: https://github.com/kossnocorp/assets-webpack-plugin/blob/master/index.js#L64

typeMap[typeName] = assetPath + asset

Solution

Either use the path package:

typeMap[typeName] = path.join(assetPath, asset);

or only a slash between:

typeMap[typeName] = assetPath + "/" + asset;

I think the first choice is the cleaner solution.

Example configuration for webpack-dev-server?

I've written this little PHP script for generating the HTML source code from the webpack-assets.json file:

function ($name) {
    static $assets;
    if($assets === null) {
        $assets = Json::loadFile(base_path('webpack-assets.json'));
    }
    if(!isset($assets[$name])) {
        throw new \Exception("Asset '$name' does not exist");
    }
    $out = [];
    foreach($assets[$name] as $kind => $path) {
        switch($kind) {
            case 'js':
                $out[] = '<script' . \Ptilz\Html::attrs(['src' => $path]) . '></script>';
                break;
            case 'css':
                $out[] = '<link' . \Ptilz\Html::attrs(['rel' => 'stylesheet', 'type' => 'text/css', 'href' => $path]) . '>';
                break;
            default:
                throw new \Exception("Unsupported asset kind: $kind");
        }
    }
    return implode("\n", $out);
}

Which works great with webpack -w, but since output doesn't contain http://localhost:8080/... it won't work with webpack-dev-server. I know it's possible to adjust the publicPath in webpack.config.json for this, but then it'll work for one but not the other.

Is there a way to support both webpack and webpack-dev-server with one configuration file?

Do not overwrite assets file - just update it

When I transfer multiple configurations to webpack I will get hash only for last entry:

var compiler = webpack(config1, config2, ...);

It would be better if the plugin will not overwrite assets file but just update it (i.e. through object-assign module).

Build directory compiled prior to assets.json creates disconnect

i'm attempting to use this plugin in my React/Fluxible project, however because the assets.json file is created after the bundle has already been compiled, the included assets.json file is not found during the build. If i redo the build process a second time without making changes it works. Not sure if this is an issue with the plugin or my configuration. If assets.json is required before the build process, but can't be built until the hash has been created, how's the flow supposed to go?

var config = {
  resolve: {
    extensions: ['', '.js']
  },
  entry: './app/client.js',
  output: {
    path: './build/js',
    publicPath: '/public/js/',
    filename: '[name]-[hash].js'
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] },
      { test: /\.json$/, loader: 'json-loader'},
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css!autoprefixer!rework')},
      { test: /\.(jpg)$/, loader: 'file-loader' },
      { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
    ]
  },
  plugins: [
    new ExtractTextPlugin('app-[hash].css'),
    new AssetsPlugin({
      path: path.join(__dirname, 'app', 'configs'),
      filename: 'assets.json'
    })
  ],
  rework: {
    use: [
      at2x(),
      inherit(),
      reworkNPM(),
      media(),
      parent,
      vars({})
    ]
  },
  stats: {
    colors: true
  },
  devtool: 'source-map',
  watch: true,
  keepalive: true
};

miss some css file manifest

i have two entry,one for app another for vendor,i debug you code :
stats.assetsByChunkName is:
{ apps: [ 'apps.bundle.js', 'apps.bundle.css', 'apps.bundle.scss.css', 'apps.bundle.js.map', 'apps.bundle.css.map', 'apps.bundle.scss.css.map' ], vendors: [ 'vendors.bundle.js', 'vendors.bundle.css', 'vendors.bundle.scss.css', 'vendors.bundle.js.map', 'vendors.bundle.css.map', 'vendors.bundle.scss.css.map' ] }
output is:
{ apps: { js: 'http://localhost:4001/dist/apps.bundle.js', css: 'http://localhost:4001/dist/apps.bundle.scss.css' }, vendors: { js: 'http://localhost:4001/dist/vendors.bundle.js', css: 'http://localhost:4001/dist/vendors.bundle.scss.css' } }
it miss file endswith 'scss.css'
i use two 'extract-text-webpack-plugin' one for css and another for scss,so one entry has two css file.
my webpack setting:
{
entry:{
vendors:xxx
apps:xxxx
}
..
plugins:[
new ExtractTextPlugin({
filename:'[name].bundle.css'
}),
new ExtractTextPlugin({
filename:'[name].bundle.scss.css'
})
]
}

Writes file name of source maps, not the JS files themselves

Command I'm running:

NODE_ENV=development webpack --progress --colors --watch -d

Webpack output:

Hash: 9b913c8594ce98e06b21
Version: webpack 1.8.5
Time: 2638ms
                              Asset     Size  Chunks             Chunk Names
    desktop.js?9b913c8594ce98e06b21  75.8 kB       0  [emitted]  desktop
     mobile.js?9b913c8594ce98e06b21    62 kB       1  [emitted]  mobile
desktop.js.map?9b913c8594ce98e06b21   122 kB       0  [emitted]  desktop
 mobile.js.map?9b913c8594ce98e06b21  95.8 kB       1  [emitted]  mobile

webpack-assets.json:

{"desktop":"desktop.js.map?9b913c8594ce98e06b21","mobile":"mobile.js.map?9b913c8594ce98e06b21"}

If I disable outputting of source maps, it works fine.

Webpack 2 path to files without slash

in webpack v 1 all was fine, but in v2 generate json without slash

new AssetsPlugin({
  prettyPrint: true,
  path: "../public/",
}),

slash is missing:

"main": {
  "js": "/webpackmain.0d202c04838160cdbeed.js",
  "css": "/webpackcss/main-7852e8fe6c98d01cc98d.css"
}

list .gz files

Hi and thanx for this great repo
I wanna use CompressionPlugin for prod webpack config along with assets-webpack
The problem is the webpack-assets.json is only included js files not .gz files

how can achieve that?

`

plugins: [
    ...Base.plugins,
    new AssetsPlugin({
        path: path.resolve('./dist'),
        filename: 'assets.json',
        prettyPrint: true,
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"production"'
        },
        __CLIENT__: true,
        __SERVER__: false,
        __DEV__: false,
    }),
     new CompressionPlugin({
         asset: '[path].gz[query]',
         algorithm: 'gzip',
         test: /\.jsx?$|\.css$|\.(scss|sass)$|\.html$/,
         threshold: 8192,
         minRatio: 0.8,
         deleteOriginalAssets: true
     }),
]

`

css assets list unnecessary js file

Hello,

Just wondering if it's possible to get only css listing in the json output when there is only a css in the entry. Actually it's output both a css and a js.

input for webpack:

entry: {
    inline: [
      './scss/inline_bundle.scss'
    ]
  }

assets.json output:

"inline":{
  "js":"/assets/js/inline.96191b01.js",
  "css":"/assets/css/inline.f3605b91.css"
}

would like:

"inline":{
  "css":"/assets/css/inline.f3605b91.css"
}

That would be pretty useful when to link assets with a simple php class.

Thanks

Not creating assets json running webpack dev server after 3.6.1

Have to make some changes in config after update from 3.6.0, but running through webpack is working fine now(production build), it creates json with assets, but using webpack dev server is not updating generated assets json file. Hot to fix this and return to an old behavior?

Does it work with chunked CSS?

I have single chunked CSS + JS, but it appear to only can output once.

{"builder":"/css/builder-ff7029d929fbad65d968.css"}

The JS somehow is missing like /js/builder-ff7029d929fbad65d968.js

processOutput in combination with Watch Mode leads to nested data

When using
"watch: true" and "keepalive: true"

process output leads to strange effects.

new AssetsPlugin({
                filename: './config/assets.json',
                processOutput: (assets) => JSON.stringify({assets}),
                prettyPrint: true,
            }),

It looks like processOutputs somehow manipulates something stateful. After each run the config gets nested another level.

{
  "assets": {
    "assets": {
      "assets": {
        "admin": {
          "js": "admin.js",
          "css": "admin.css"
        },
        "main": {
          "js": "main.js",
          "css": "main.css"
        }
      },
      "admin": {
        "js": "admin.js",
        "css": "admin.css"
      },
      "main": {
        "js": "main.js",
        "css": "main.css"
      }
    },
    "admin": {
      "js": "admin.js",
      "css": "admin.css"
    },
    "main": {
      "js": "main.js",
      "css": "main.css"
    }
  }
}

Update tags in github

This isn't an issue with the package itself not a big issue either.
I just wanted to remind that the tags are missing in github for the latest versions.

I installed 3.8.3 even though the latest tagged release on github is only 3.7.1

Plugin works wrong

Input:

entry: {
  bundle: "./frontend/scripts/app",
  vendors: ["react", "react-router"],
},

plugins: [
  new Webpack.optimize.CommonsChunkPlugin("vendors", "vendors-[hash].js"),
  new ExtractTextPlugin("[name]-[hash].css"), 
  new SaveAssetsJsonPlugin({filename: "assets.json"}), // path: sharedDir,
],

Result:

{"bundle":"/public/bundle-7465a6987c4d4a814e96.css",
 "vendors":"/public/vendors-7465a6987c4d4a814e96.js"}

Ought to contain 3 bundles (2 JS + 1 CSS).
Contains only 2... with CSS and JS files messed up... ๐Ÿ˜ž

get manifest.json key inside index.html

hey,

i'm having a static index.html (not generated by webpack)

inside it i would like to include one of entries declared in webpack

    entry: {
        admin: './assets/admin/index.js',
        app: './assets/app/index.js',
        vendor: ['jquery', 'd3']
    }

the manifest.json is generated, but i have no ideea how i could parse html on each build and push targeted entry.

any ideea about what plugin could parse index.html and write out from manifest.json ?

Webpack 4 deprecation warning

Hi
I have this warning

(node:3792) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead

Modules

"assets-webpack-plugin": "^3.5.1",
"webpack": "^4.1.1",

Thank you

Reduce package size

Package contains unnecessary directories and files - test, .travis.yml and maybe others. I can do PR if your accept this issue.

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.