Write problem & solution of front end we may meet. 主要记录前端学习和实践过程中踩过的各种坑.
This project is maintained by soolaugust
以下所有示例的js版本都是ES6+,如果使用的ES5,则需要相应的替换,例如将const换成var
webpack主要用于对JavaScript进行打包。
webpack --config webpack.***.js
webpack (会寻找配置文件webpack.config.js)
webpack.***.js 为相应的配置文件,具体可参考 配置-webpack中文文档
const path = require('path');
module.exports = {
mode: 'development',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
webpack主要是针对javascript进行打包,所以默认情况下只会对javascript进行打包,如果需要打包成html,需要使用 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',
})
]
}
这时需要引入外部插件 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),
]
}
如果出现 AssertionError [ERR_ASSERTION]: The HtmlWebpackInlineSourcePlugin does not accept any options , 说明你使用的是旧的版本, 使用最新版本或者将 new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin) 转成 new HtmlWebpackInlineSourcePlugin()
需要使用 css-loader 和 style-loader
npm install style-loader --save-dev
npm install --save-dev css-loader
Step 1: 在js中导入css
const cssFile = require('demo.css');
Step 2: 在配置文件中加入css loader
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
需要使用 url-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: ['url-loader']
}
]
}
}
有时候最终只需要一个html,这时需要将原先需要的图片都编入html中。这时需要配合使用 html-loader 和 url-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: ['url-loader']
}, {
test: /\.(html)$/,
use: ['html-loader']
]
}
}