前端工程化
阿新 • • 發佈:2020-10-25
構建工具webpack五大核心概念:
入口:entry:‘./src/index.js’
出口:output:{path:path,filename:name}
引入方式:配置檔案、import、cli
Loader:module:{
rules:[
{test:/\.txt$/,use:'raw-loader}
]
}
外掛:plugins:[
new HtmlWbpackPlugin(template:'./src/index.html'))
]
模式/相容性:mode:development procution
<!--===============================================-->
webpack安裝和使用
初始化專案
npm init -y 快速建立node專案
安裝方式
npm install -g/-D webpack webpack-cli
npx webpack --version 檢視版本
webpack.config.js
const path = require('path') const htmlWebpackPlugin = require('html-webpack-plugin') const webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports= { //模式/相容性 mode: 'production', //入口 entry: './src/index.js', //出口 output: { filename: 'bundle.js', path: path.join(__dirname, './dist') }, //laoders module: { rules: [ { //node-sass 的安裝 test: /\.(scss|sass)$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, { test:/\.js$/, loader: 'babel-loader' }, { test: /\.(png|svg|jpg|gif)$/, use: ['file-loader'] }, { test: /\.(woff|woff2|eot|otf)$/, use: ['file-loader'] } ] }, devServer: { hot: true, contentBase: './dist', port: 8900 }, //plugins new webpack.HotModuleReplacementPlugin 熱模組更新 plugins: [ new htmlWebpackPlugin({ filename: 'index.html', template: './index.html' }), new webpack.HotModuleReplacementPlugin(), new CopyWebpackPlugin({ patterns: [ { from: path.join(__dirname, './src/assets'), to: 'assets' } ] }) ] }
gulp構建工具:
gulpfile.js
const { src, dest, series, watch } = require('gulp') const browserSync = require('browser-sync').create() const reload = browserSync.reload const plugins = require('gulp-load-plugins')() const del = require('del') function js (cb) { src('js/*.js') .pipe(plugins.uglify()) .pipe(dest('./dist/js')) .pipe(reload({ stream: true })) cb() } function css (cb) { src('./scss/*.scss') .pipe(plugins.sass({ outputStyle: 'compressed' })) .pipe(plugins.autoprefixer({ cascade: false, remove: false })) .pipe(dest('./dist/css')) .pipe(reload({ stream: true })) console.log('this is css') cb() } function watcher () { watch('js/*.js', js) watch('scss/*.scss', css) } function clean (cb) { del('./dist') cb() } //server function serve (cb) { browserSync.init({ server: { baseDir: './' } }) cb() } exports.scripts = js exports.styles = css exports.clean = clean //npx gulp --tasks exports.default = series([ clean, js, css, serve, watcher ])