'[name]。[chunkhash] .js',名字不起作用

时间:2018-01-17 10:24:57

标签: javascript webpack webpack-2

我尝试使用'[name]。[chunkhash] .js'构建js文件,但输出文件不包含名称

这是我的输出配置

webpackConfig.output = {
  filename: __DEV__ ? '[name].js' : '[name].[chunkhash].js',
  path: paths.dist(),
  publicPath: config.compiler_public_path
}

我最近将webpack更新到v3,之后我遇到了这个问题

更新1

条目配置:

webpackConfig.entry = {
      app: __DEV__? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`) : APP_ENTRY_PATHS,
      vendor: config.compiler_vendor
}

更新2

import webpack from 'webpack'
import path from 'path'
const project = require('../project.config')
const inProject = path.resolve.bind(path, project.basePath)
const inProjectSrc = (file) => inProject(project.srcDir, file)
import PreloadWebpackPlugin from 'preload-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import config from '../config'
import _debug from 'debug'
const debug = _debug('app:webpack:config')
const paths = config.utils_paths
const {__DEV__, __PROD__, __TEST__} = config.globals
debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: project.sourcemaps ? 'source-map' : false,
  resolve: {
    modules: [
      inProject(project.srcDir),
      'node_modules',
    ],
    extensions: [ '*','.js', '.jsx', '.json']
  },
  module: {rules:[]}
}

webpackConfig.node = {
  fs: 'empty',
  net: 'empty',
  tls: 'empty'
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY_PATHS = [
  paths.client('main.js')
]

webpackConfig.entry = {
  app: __DEV__
    ? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`)
    : APP_ENTRY_PATHS,
  vendor: config.compiler_vendor
}

// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
  filename: __DEV__ ? '[name].js' : '[name].[chunkhash].js',
  path: paths.dist(),
  publicPath: config.compiler_public_path
}


// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
  new webpack.DefinePlugin(config.globals),
  new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery"
  }),


  new HtmlWebpackPlugin({
    template: paths.client('index.html'),
    hash: false,
    favicon: paths.client('../src/static/assets/favicon.ico'),
    filename: 'index.html',
    inject: 'body',
    minify: {
      collapseWhitespace: true
    }
  })
]

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin (),

  )
} else if (__PROD__) {
  debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.DefinePlugin({ // <-- key to reducing React's size
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.DedupePlugin(), //dedupe similar code
    // new webpack.optimize.AggressiveMergingPlugin(),//Merge chunks
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),//Merge chunks
    new PreloadWebpackPlugin(),
  new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        warnings: false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor']
    })
  )
}


// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    query: {
      cacheDirectory: true,
      plugins: [
        'transform-runtime',
        'babel-plugin-transform-class-properties',
      ],
      presets: [
        'babel-preset-react',
        ["es2015", {"modules": false}],
        'stage-0',
        ['babel-preset-env', {
          modules: false,
          targets: {
            ie9: true,
          },
          uglify: true,
        }],
      ]
    },
  }],
})


// ------------------------------------
// Style Loaders
// ------------------------------------


const extractStyles = new ExtractTextPlugin({
  filename: 'styles/[name].[contenthash].css',
  allChunks: true,
  disable: __DEV__,
})

webpackConfig.module.rules.push({
    test: /\.(css)$/,
    loader: extractStyles.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              sourceMap: project.sourcemaps,
              minimize: {
                autoprefixer: {
                  add: true,
                  remove: true,
                  browsers: ['last 2 versions'],
                },
                discardComments: {
                  removeAll : true,
                },
                discardUnused: false,
                mergeIdents: false,
                reduceIdents: false,
                safe: true,
                sourcemap: project.sourcemaps,
              },
            },
          }
          ]
      }
    )
  },
  {
    test: /\.(scss|sass)$/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: [
        {
          loader: 'css-loader',
          options: {
            modules: true,
            importLoaders: 1,
            localIdentName: '[name]__[local]___[hash:base64:5]'
          }
        },
        'postcss-loader',
        'sass-loader'
      ]
    })
  })

webpackConfig.plugins.push(extractStyles)
// File loaders
/* eslint-disable */
// Images
// ------------------------------------
webpackConfig.module.rules.push({
  test    : /\.(png|jpg|gif)$/,
  loader  : 'url-loader',
  options : {
    limit : 8192,
  },
})

// Fonts
// ------------------------------------
;[
  ['woff', 'application/font-woff'],
  ['woff2', 'application/font-woff2'],
  ['otf', 'font/opentype'],
  ['ttf', 'application/octet-stream'],
  ['eot', 'application/vnd.ms-fontobject'],
  ['svg', 'image/svg+xml'],
].forEach((font) => {
  const extension = font[0]
  const mimetype = font[1]

  webpackConfig.module.rules.push({
    test    : new RegExp(`\\.${extension}$`),
    loader  : 'url-loader',
    options : {
      name  : 'fonts/[name].[ext]',
      limit : 10000,
      mimetype,
    },
  })
})

if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.rules.filter((loader) =>
    loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0]))
  ).forEach((loader) => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    Reflect.deleteProperty(loader, 'loaders')
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )
}
export default webpackConfig

1 个答案:

答案 0 :(得分:0)

很难说出你的配置文件中有什么问题,因为有很多外部变量,我不知道它们的值。

所以,也许你可以看看我的基本webpack项目

https://github.com/littlee/webpack-3-project

  • 输出[hash:8]。[name] .js file
  • css / less使用生产中的提取文本插件导入
  • webpack-dev-server设置
  • 图片加载器
  • 字体加载器
  • html插件生成html文件

更新20180122:

getEntry会将数组从pages.js转换为条目配置对象

pages.js

module.exports = ['index', 'another', 'and_so_on']

getEntry将返回

{
  index: './js/index.js',
  another: './js/another.js',
  and_so_on: './js/and_so_on.js'
}

在开发模式下,它将添加webpack-dev-server的必备条目

我使用这个项目创建一个多页面网站,所以我使用多个条目配置。

我用webpack-html-plugin来生成html文件,默认情况下,它会包含html中的所有输出文件。

但是我希望每个html都包含自己的bundle文件,所以在使用这个插件时我必须添加'chunks'配置