Home > Web Front-end > JS Tutorial > body text

Optimized use of webpack scaffolding

php中世界最好的语言
Release: 2018-05-02 14:38:28
Original
1342 people have browsed it

This time I will bring you the optimized use of webpack scaffolding. What are the precautions for optimizing the use of webpack scaffolding? The following is a practical case, let's take a look.

Optimization category

  1. Style separation

  2. Separation of third-party resources

  3. Differentiate development environment

  4. Hot update

  5. Extract public code

1. CSS separation

npm install extract-text-webpack-plugin -D
Copy after login
webpack.config.js

Separate css, less, and sass files separately from the packaged file

+ let cssExtract = new ExtractTextWebpackPlugin({
+ filename: 'css.css',
+ allChunks: true
+ });
+ let sassExtract = new ExtractTextWebpackPlugin('sass.css')
+ let lessExtract = new ExtractTextWebpackPlugin('less.css')
Copy after login
In webpack.config.js Add a separate rule,

  1. test:

    regular expression # that matches the extension of the

    processed file
  2. ##include/exclude Manually specify the folders that must be processed or block the folders that do not need to be processed
  3. {
     test: /\.css$/,
     use: cssExtract.extract({
     fallback: "style-loader",
     use: ['css-loader?minimize','postcss-loader'],
     publicPath: "/dist"
     }),
     include:path.join(dirname,'./src'),
     exclude:/node_modules/
    },
    {
     test: /\.scss$/,
     use: sassExtract.extract({
     fallback: "style-loader",
     use: ["css-loader?minimize","sass-loader"],
     publicPath: "/dist"
     }),
     include:path.join(dirname,'./src'),
     exclude:/node_modules/
    },
    {
     test: /\.less$/,
     loader: lessExtract.extract({
     use: ["css-loader?minimize", "less-loader"]
     }),
     include:path.join(dirname,'./src'),
     exclude:/node_modules/
    },
    Copy after login
  4. Then run the webpack command and an error will be reported

compilation. mainTemplate.applyPluginsWaterfall is not a function

Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

The research concluded that the reason why webpack was upgraded to v4 but the corresponding plug-in was not upgraded.

Solution: Install the specified version of dependencies

"html-webpack-plugin": "^3.0.4"
"extract-text-webpack-plugin": "^4.0.0-beta.0"
Copy after login

resolve

After specifying the extension, you don’t need to add the file extension when requiring or importing , will try to add extensions in order to match

resolve: {
 //引入模块的时候,可以不用扩展名
 extensions: [".js", ".less", ".json"],
 alias: {//别名
 "bootstrap": "bootstrap/dist/css/bootstrap.css"
 }
}
Copy after login

Listen to file modification

Used in webpack mode, not used in webpack-dev-server mode, you can change watch to false

watchOptions: {
 ignored: /node_modules/,
 aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高
 poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次
}
Copy after login

Extract public code

optimization: {
 splitChunks: {
 cacheGroups: {
 commons: {
  chunks: "initial",
  minChunks: 2,
  maxInitialRequests: 5, // The default limit is too small to showcase the effect
  minSize: 0 // This is example is too small to create commons chunks
 },
 vendor: {
  test: /node_modules/,
  chunks: "initial",
  name: "vendor",
  priority: 10,
  enforce: true
 }
 }
 }
 }
Copy after login

Separate react react-dom ant public code

Method 1: externals

Introduce a third-party resource library to the page, and then use externals to prevent certain imported packages from being packaged into the bundle. Instead, obtain these external dependencies from the outside at runtime. .

<script src="https://cdn.bootcss.com/react/16.4.0-alpha.0911da3/cjs/react.production.min.js"></script>
<script src="https://cdn.bootcss.com/react-dom/16.4.0-alpha.0911da3/cjs/react-dom-server.browser.production.min.js"></script>
externals: { 'react': 'React', 'react-dom': 'ReactDOM', // 提出ant design的公共资源, }
Copy after login

Method 2: DLL

DLL was written in the previous article, but it kept appearing after packaging.

I later found out that it was There are no resources introduced on the page. . . . (I always thought webpack would automatically generate it on the page....)

Introduced

<script src="./vendor/react.dll.js"></script>
Copy after login

into the index.html file and the separation was successful! Up code

webpack.base.js

var path = require('path');
var webpack = require('webpack');
var ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin')
let cssExtract = new ExtractTextWebpackPlugin({
 filename: 'css.css',
 allChunks: true
});
let sassExtract = new ExtractTextWebpackPlugin('sass.css')
let lessExtract = new ExtractTextWebpackPlugin('less.css')
module.exports = {
 entry:'./src/index.js',
 output: {
 path: path.resolve(dirname, './dist'),
 filename: 'bundle.[hash:8].js',
 publicPath: ''
 },
 resolve: {
 //引入模块的时候,可以不用扩展名
 extensions: [".js", ".less", ".json"],
 alias: {//别名
 "bootstrap": "bootstrap/dist/css/bootstrap.css"
 },
 modules: [path.resolve(dirname, 'node_modules')]
 },
/* externals: {
 'react': 'React',
 'react-dom': 'ReactDOM',
 // 提出ant design的公共资源
 //'antd': 'antd',
 },*/
 devtool: 'source-map',
 devServer: {
 contentBase:path.resolve(dirname,'dist'),
 publicPath: '/',
 port: 8080,
 hot:true,
 compress:true,
 historyApiFallback: true,
 inline: true
 },
 watch: false, //只有在开启监听模式时,watchOptions才有意义
 watchOptions: {
 ignored: /node_modules/,
 aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高
 poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次
 },
 optimization: {
 splitChunks: {
 cacheGroups: {
 commons: {
  chunks: "initial",
  minChunks: 2,
  maxInitialRequests: 5, // The default limit is too small to showcase the effect
  minSize: 0 // This is example is too small to create commons chunks
 },
 vendor: {
  test: /node_modules/,
  chunks: "initial",
  name: "vendor",
  priority: 10,
  enforce: true
 }
 }
 }
 },
 module: {
 rules:[
 {
 test: /\.js$/,
 use: {
  loader:'babel-loader',
  options: {
  presets: ['env','es2015', 'react'],
  }
 },
 include:path.join(dirname,'./src'),
 exclude:/node_modules/
 },
 {
 test: /\.css$/,
 use: cssExtract.extract({
  fallback: "style-loader",
  use: ['css-loader?minimize','postcss-loader'],
  publicPath: "/dist"
 }),
 include:path.join(dirname,'./src'),
 exclude:/node_modules/
 },
 {
 test: /\.scss$/,
 use: sassExtract.extract({
  fallback: "style-loader",
  use: ["css-loader?minimize","sass-loader"],
  publicPath: "/dist"
 }),
 include:path.join(dirname,'./src'),
 exclude:/node_modules/
 },
 {
 test: /\.less$/,
 loader: lessExtract.extract({
  use: ["css-loader?minimize", "less-loader"]
 }),
 include:path.join(dirname,'./src'),
 exclude:/node_modules/
 },
 {
 test: /\.(html|htm)/,
 use: 'html-withimg-loader'
 },
 {
 test: /\.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)/,
 use: {
  loader:'url-loader',
  options:{
  limit: 5 * 1024,
  //指定拷贝文件的输出目录
  outputPath: 'images/'
  }
 }
 }
 ]
 },
 plugins: [
 //定义环境变量
 new webpack.DefinePlugin({
 development: JSON.stringify(process.env.NODE_ENV)
 }),
 new CleanWebpackPlugin(['dist']),
 cssExtract,
 lessExtract,
 sassExtract,
 new HtmlWebpackPlugin({
 title: 'React Biolerplate by YuanYuan',
 template: './src/index.html',
 filename: `index.html`,
 hash: true
 }),
 new webpack.DllReferencePlugin({
 manifest: path.join(dirname, 'vendor', 'react.manifest.json')
 }),
 new CopyWebpackPlugin([{
 from: path.join(dirname,'vendor'),//静态资源目录源地址
 to:'./vendor' //目标地址,相对于output的path目录
 }]),
/* new webpack.optimize.CommonsChunkPlugin({
 name: 'common' // 指定公共 bundle 的名称。
 + })*/
 new webpack.HotModuleReplacementPlugin(), // 热替换插件
 new webpack.NamedModulesPlugin() // 执行热替换时打印模块名字
 ]
};
Copy after login

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');//用来合并配置文件
const base = require('./webpack.base');
let other = '';
//console.log(process.env.NODE_ENV )
if (process.env.NODE_ENV == 'development') {
 other = require('./webpack.dev.config');
} else {
 other = require('./webpack.prod.config');
}
//console.log(merge(base, other));
module.exports = merge(base, other);
webpack.prod.config.js
const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
 output: {
 filename: 'bundle.min.js',
 },
 plugins: [
 new UglifyJSPlugin({sourceMap: true})
 ]
}
Copy after login

Original scaffolding address

Optimized scaffold address

# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the usage from dev to prd


Detailed explanation of the steps to use dev-server in webpack

The above is the detailed content of Optimized use of webpack scaffolding. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template