Write problem & solution of front end we may meet. 主要记录前端学习和实践过程中踩过的各种坑.
This project is maintained by soolaugust
All codes are based on ES6+, if you are using ES5, please try to replace them, e.g. replace const with var
webpack is a static module bundler for modern Javascript applications.
webpack --config webpack.***.js
webpack //will find default config file:webpack.config.js
webpack.***.js is the config file of webpack,reference: Configuration - Webpack
const path = require('path');
module.exports = {
mode: 'development',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
As webpack serve Javascript default, so if we want to serve webpack bundles into html file, we may need external plugin: html-webpack-plugin;
npm i --save-dev html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin()
]
}
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
})
]
}
At this time, we need another plugin: html-webpack-inline-source-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
inlineSource: '.(js)$',
template: 'index.html',
}),
new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
]
}
If meet this error: AssertionError [ERR_ASSERTION]: The HtmlWebpackInlineSourcePlugin does not accept any options , That means you are using a older version, try to use newer version or change new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin) to new HtmlWebpackInlineSourcePlugin()
We need these plugin: css-loader & style-loader
npm install style-loader --save-dev
npm install --save-dev css-loader
Step 1: import css file in entry js file.
const cssFile = require('demo.css');
Step 2: add css loader in webpack config file.
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
We need this loader: url-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: ['url-loader']
}
]
}
}
As some times, we only need a html finally, so we may need to serve all images into generated html, then we need use these loader: html-loader & url-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: ['url-loader']
}, {
test: /\.(html)$/,
use: ['html-loader']
]
}
}