yarn add webpack webpack-cli -D
新建 webpack.config.jscss
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') } };
package.jsonhtml
{ "name": "webpack-demo", "version": "1.0.0", "description": "webpack demo project", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" // 增長 }, "author": { "name": "wubh2012" }, "license": "MIT", "devDependencies": { "webpack": "^4.39.2", "webpack-cli": "^3.3.6" } }
使用 命令yarn build
或 npx run build
運行node
yarn add style-loader css-loader -D yarn add node-sass sass-loader -D yarn add file-loader -D
配置 webpack.config.js
webpack
{ test: /\.css|.scss|.sass$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { hmr: devMode, }, }, 'css-loader', 'sass-loader', ]}, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }
yarn add mini-css-extract-plugin -D yarn add optimize-css-assets-webpack-plugin -D yarn add cssnano -D
webpack.config.js
web
const MiniCssExtractPlugin = require('mini-css-extract-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); plugins:[ // 獨立css文件 new MiniCssExtractPlugin({ filename: devMode ? '[name].css' : '[name].[hash].css', chunkFilename: devMode ? '[id].css' : '[id].[hash].css', }), // 壓縮css new OptimizeCSSAssetsPlugin({ assetNameRegExp: /\.css\.*(?!.*map)/g, cssProcessor: require('cssnano'), cssProcessorPluginOptions: { preset: ['default', { discardComments: { removeAll: true } }], }, canPrint: true }) ]
yarn add html-webpack-plugin -D yarn add clean-webpack-plugin -D yarn add webpack-dev-server -D
package.jsonjson
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "watch": "webpack --watch", "start": "webpack-dev-server", "build": "webpack" },
webpack.config.js瀏覽器
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const APPDIR = 'src/'; module.exports = { mode: 'development', plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: path.resolve(__dirname, APPDIR, 'index.html'), filename: 'index.html', inject: 'body' }) ],
運行 yarn start
,而後用瀏覽器打開 localhost:8080
sass
yarn add @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/runtime babel-loader -D
// webpack.config 配置 { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: ['@babel/plugin-transform-runtime'] } } }