niaogege / niaogege.github.io

博客,记录生活,记录code
http://niaogege.cn
2 stars 1 forks source link

webpack内置的一些plugin以及用途 #12

Open niaogege opened 6 years ago

niaogege commented 6 years ago

HtmlWebpackPlugin简化了HTML文件的创建,以便为您的webpack包提供服务。 这对于在文件名中包含每次会随着变异会发生变化的哈希的webpack bundle尤其有用。 您可以让插件为您生成一个HTML文件,使用lodash模板提供您自己的模板,或使用您自己的loader。 new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index, template: 'index.html', inject: true, minify: { removeComments: true, //去掉注释 collapseWhitespace: true, //压缩空格 removeAttributeQuotes: true //去除属性引用 // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }),

niaogege commented 6 years ago

DefinePlugin:允许在编译时(compile time)配置的全局常量 new webpack.DefinePlugin({ 'process.env': env }), 这可能会对开发模式和发布模式的构建允许不同的行为非常有用。如果在开发构建中,而不在发布构建中执行日志记录,则可以使用全局常量来决定是否记录日志。这就是 DefinePlugin 的用处,设置它,就可以忘记开发和发布构建的规则

niaogege commented 6 years ago

CommonsChunkPlugin,是一个可选的用于建立一个独立文件(又称作 chunk)的功能,这个文件包括多个入口 chunk 的公共模块。通过将公共模块拆出来,最终合成的文件能够在最开始的时候加载一次,便存起来到缓存中供后续使用。这个带来速度上的提升,因为浏览器会迅速将公共的代码从缓存中取出来,而不是每次访问一个新页面时,再去加载一个更大的文件。

niaogege commented 6 years ago

今天遇到一个很诡异的问题,尼玛,什么需求都有!!只能说自己webpack还不到家,上代码 build: { env: require('./prod.env'), index: path.resolve(dirname, '../dist/index.html'), //编译之后的存放路径 assetsRoot: path.resolve(dirname, '../dist'),//编译生成之后的dist目录 assetsSubDirectory: 'static',//存放的 static路径 assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to true, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // npm run build --report // Set to true or false to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report },

niaogege commented 6 years ago

DefinePlugin 允许创建一个在编译时可以配置的全局常量; 比如webpack可这么配置: new webpack.DefinePlugin({ 'process.env': config.dev.env, 'PRODUCTION':JSON.stringify(false), 'VERSION':JSON.stringify('开发环境中的版本1.1.1')//因为这个插件直接执行文本替换,给定的值必//须包含字符串本身内的实际引号。通常,有两种方式来达到这个效果,使用 '"production"', 或者使用 //JSON.stringify('production')。 }),

niaogege commented 6 years ago

CommonsChunkPlugin 可以用于将模块分离到单独的文件中。然而 CommonsChunkPlugin 有一个较少有人知道的功能是,能够在每次修改后的构建结果中,将 webpack 的样板(boilerplate)和 manifest 提取出来。通过指定 entry 配置中未用到的名称,此插件会自动将我们需要的内容提取到单独的包中: