웹 팩 4x, 가...
1. \ # 그의 핵심 기능 부터 살 펴 보 자. 왜 그 를 쓰 는 거 야? \ #
1. 패키지: 여러 자바 script 파일 을 하나의 파일 로 포장 하여 서버 압력 과 다운로드 대역 폭 을 줄 일 수 있 습 니 다.
2. 변환: 확장 언어 를 일반적인 자 바스 크 립 트 로 변환 하여 브 라 우 저가 순조롭게 실 행 될 수 있 도록 합 니 다.
3. 최적화: 전단 이 점점 복잡 해 지면 성능 에 도 문제 가 생 길 수 있 고 WebPack 도 성능 을 최적화 하고 향상 시 키 는 책임 을 지기 시작 했다.
4. Webpack 은 생산 환경 에서 중요 한 역할 을 하 는데 http 의 요청 수 를 줄 이 는 것 이다.
위의 세 가 지 는 바로 그것 이다.
2. 웹 팩 (현재 최신 버 전 4.8.3) 설치 및 환경 설정
웹 팩 이라는 녀석 은 업데이트 가 빠 르 기 때문에 버 전의 웹 팩 에 사용 되 는 명령 도 거의 다르다.
1. 전역 설치 webpack npm i webpack - g
2. 프로젝트 폴 더 에 들 어가 프로젝트 를 초기 화하 고 pake. json 파일 을 만 들 기 위해 서 입 니 다.npm init 계속 리 턴 하면 됩 니 다.
3. 웹 팩 을 설치 한 의존 nodemodules; npm i -D webpack
4. 전역 에 webpack - cli 설치 하기;npm i webpack-cli -g
5. 기본 개발 환경 을 설정 하고 mode (모델) 를 설정 하 며 '개발 환경 (production)' 인지 '생산 환경 (development)' 인지 지정 합 니 다.물론 지속 적 인 개발 에 있어 서 개발 환경 을 우선 설정 해 야 한다.webpack --mode development;
6. 나중에 포장 하면 webpack -- mode development 를 입력 할 수 있 습 니 다.그러나 매번 이렇게 입력 하 는 것 이 매우 번거롭다.pake. json 글 의 script 에서 "dev" 를 설정 합 니 다. "webpack -- mode development" 과 "build": "webpack -- mode production";
npm run dev 를 입력 하면 프로젝트 가 자동 으로 생 성 된 dist 폴 더 에 압축 할 수 있 습 니 다.npm run build 포장 생산 환경;
7. 모든 개발 파일 은 src 폴 더 아래 있어 야 합 니 다. 웹 팩 4 의 기본 입구 폴 더 는 src 이기 때 문 입 니 다.
주의:
1. webpack - cli 는 전역 적 으로 설치 해 야 합 니 다. 그렇지 않 으 면 webpack 명령 을 사용 할 수 없습니다.
2. 웹 팩 도 전역 적 으로 설치 해 야 합 니 다. 그렇지 않 으 면 웹 팩 명령 을 사용 할 수 없습니다.
3. webpack 4. x 에서 webpack. config. js 와 같은 설정 파일 은 필요 하지 않 습 니 다.
4. 기본 입구 파일 은. / src / index. js 이 고 기본 출력 파일 은. / dist / main. js 입 니 다.
3. webpack. config. js | webpack - cli init 설정
Will your application have multiple bundles? No // string, object
2. Which module will be the first to enter the application? [example: './src/index'] ./src/index //
3. What is the location of "app"? [example: "./src/app"] './src/index' //
4. Which folder will your generated bundles be in? [default: dist]: // , dist
5. Are you going to use this in production? No // (Yes 9 'config', No 'prod')
6. Will you be using ES2015? Yes // ES6 => ES5
7. Will you use one of the below CSS solutions? CSS // , loader
8. If you want to bundle your CSS files, what will you name the bundle? (press enter to skip) //
9. Name your 'webpack.[name].js?' [default: 'config']: // webpack.config.js
Congratulations! Your new webpack configuration file has been created!
webpack. config. js 일람
// path
const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');//JS , uglify
const htmlPlugin= require('html-webpack-plugin');//html
// const extractTextPlugin = require('exrract-text-plugin');//extract-text-webpack-plugin CSS
// __dirname node.js , 。
var website = {
publicPath:"http://localhost:5252/"
}
module.exports = {
devtool: 'eval-source-map',
// entry:__dirname + '/src/main.js',
entry:{
main:'./src/main.js'
},
output:{
//
path:path.resolve(__dirname,'dist'),//__dirname ,path.resolve()
//
// filename:'[name].js'//filename:
// filename:'[name].[chunkHash:2].js'// .js,
},
// : CSS, ,
module:{
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
// loader: [ 'style-loader', 'css-loader' ]
// :use:[
// {loader:'style-loader'},
// {loader:'css-loader'}
// ]
},
{
test:/\.(png|jpg|gif)/,
use:[{
loader:'url-loader',
options:{
limit:500000
}
}]
}
]
},
// ,
plugins:[
new uglify(),
new htmlPlugin({
minify:{
removeAttributeQuotes:true
},
hash:true,
template:'./src/index.html'
})
// new extractTextPlugin("./css/index.css")//
],
mode:'development',
// webpack
devServer: {
//
contentBase: "./dist",// || contentBase:path:path.resolve(__dirname,'dist')
// IP , IP localhost
host:'localhost',
//
compress:true,
//
port:5252,
historyApiFallback: true,//
inline: true//
}
}
3. 웹 팩: 서비스 와 핫 업데이트
서비스 npm install webpack - dev - server – save - dev 를 설치 하고 page. json 에 scripts ": {" server ":" webpack - dev - server "} 를 설정 합 니 다.
열 업데이트: 웹 팩 - dev - server 는 페이지 를 자동 으로 새로 고침 하 는 두 가지 모드 를 제공 합 니 다: npm run server, npm start 는 이 명령 을 사용 하여 pake. json 에서 scrpts 에 설정 합 니 다: "start": "웹 팩 & & 웹 팩 - dev - server -- hot - inline"
3. loaders (webpack 의 핵심):
모든 Loaders 는 npm 에 따로 설치 하고 webpack. config. js 에서 설정 해 야 합 니 다.
1. Loaders 의 설정 형:
test: 파일 을 처리 하 는 확장자 와 일치 하 는 표현 식 입 니 다. 이 옵션 은 설정 해 야 합 니 다.
use: loader 이름, 모듈 이름 을 사용 하려 면 이 옵션 을 설정 해 야 합 니 다. 그렇지 않 으 면 오류 가 발생 합 니 다.
include / exclude: 처리 해 야 할 파일 (폴 더) 을 수 동 으로 추가 하거나 처리 할 필요 가 없 는 파일 (폴 더) 을 차단 합 니 다 (선택 가능).
query: loaders 에 추가 설정 옵션 을 제공 합 니 다 (선택 가능).
4. 파일 압축 패키지 1. css 파일 압축 은 입구 파일 index. js 에서 가 져 와 dist 아래 js 파일 에 압축 할 수 있 습 니 다.
index. js'.. /. / css / index. css' 에서 import css 를 기록 합 니 다.
2. css 의 그림 길 힘 문제:
포장 한 그림 이 404 인 것 이 분명 하기 때문에 해결 방법 은 url - loader 와 file - loader 를 설치 하 는 것 입 니 다.
npm install --save-dev file-loader url-loader
file - loader: 참조 경로 문 제 를 해결 합 니 다. background 스타일 을 url 로 배경 그림 을 도입 하면 웹 팩 은 최종 적 으로 각 모듈 을 하나의 파일 로 포장 할 것 이라는 것 을 잘 알 고 있 습 니 다. 따라서 우리 스타일 의 url 경 로 는 원본 css 파일 이 있 는 경로 가 아 닌 입구 html 페이지 입 니 다. 이 문 제 는 file - loader 를 사용 하 는 것 입 니 다.해결 되 었 습 니 다. file - loader 는 프로젝트 의 url 도입 (css 뿐만 아니 라) 을 분석 할 수 있 습 니 다. 우리 의 설정 에 따라 그림 을 해당 경로 로 복사 한 다음 에 우리 의 설정 에 따라 포장 후 파일 참조 경 로 를 수정 하여 정확 한 파일 을 가리 키 도록 합 니 다.
url - loader: 그림 이 많 으 면 http 요청 을 많이 보 내 면 페이지 성능 이 떨 어 집 니 다. 이 문 제 는 url - loader 를 통 해 해결 할 수 있 습 니 다. url - loader 는 도 입 된 그림 인 코딩 을 dataurl 로 생 성 합 니 다. 그림 데 이 터 를 한 줄 로 번역 하 는 것 과 같 습 니 다. 이 문 자 를 파일 에 포장 하면 결국 이 파일 만 도입 하면 그림 에 접근 할 수 있 습 니 다. 물론 그림 데 이 터 를 한 줄 로 번역 하 는 것 과 같 습 니 다.인 코딩 이 크 면 성능 이 소 모 됩 니 다. 따라서 url - loader 는 limit 바이트 보다 작은 파일 을 Dataurl 로 변환 하고 limit 보다 큰 파일 은 file - loader 를 사용 하여 copy 를 진행 합 니 다.
url - loader 는 file - loader 를 봉 인 했 습 니 다. url - loader 는 file - loader 에 의존 하지 않 습 니 다. 즉, url - loader 를 사용 할 때 url - loader 만 설치 하면 됩 니 다. file - loader 를 설치 할 필요 가 없습니다. url - loader 에 file - loader 가 내장 되 어 있 기 때 문 입 니 다.
3. css 파일 분리
extractTextPlugin 설치; npm install extract - text - webpack -plugin@next --save-dev;
const extractTextPlugin = require("extract-text-webpack-plugin");
* * 주의: * * 최신 버 전의 웹 팩 은 업그레이드 버 전에 대응 하 는 분리 플러그 인 을 설치 해 야 하기 때문에 @ next 를 추가 해 야 합 니 다.
웹 팩. config. js 에 설치 되 어 있 습 니 다.: const extract TextPlugin = require ('extract - text - webpack - plugin');
설치 가 끝 난 후에 웹 팩. config. js 에 로드 항목 을 설정 해 야 합 니 다.
// use: [
// { loader: 'style-loader', options: { sourceMap: true } },
// { loader: 'css-loader' }
// ]
// css :
:::
use: extractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
플러그 인 설정: new extractTextPlugin ('/ css / index. css') 압축 된 파일 의 힘 설정
npm run dev 후 dist 폴 더 에서 css 를 자동 으로 생 성 하 는 것 을 볼 수 있 습 니 다.
4. css 파일 이 분리 되면 css 의 배경 그림 길이 잘못 될 수 있 습 니 다.
해결 방법 은 웹 팩. conifg. js 에서 전역 적 으로 ip 속성 을 설명 하 는 것 입 니 다.
var website ={
publicPath:"http://localhost:5200/"// ip , server
}
output( ) , publicPath;
publicPath:website.publicPath
5. html 의 그림 처리: 도로 강도 및 파일 포장
:
npm install html-withimg-loader --save
webpack.config.js loader:
{
test: /\.(htm|html)$/i,
use:[ 'html-withimg-loader']
}
, ,
6. less 파일 패키지:: less 와 less - loader npm i less - loader - D 설치
: src less ;
, js less ;
import less from '.././less/index.less';
webpack.config.js less-loader:
use: [
{loader:'css-loader'},
{loader:'less-loader'} // js less css ;
]
7. jslabel 변환:: cnpm install -- save - dev babel - core babel - loader babel - preset - es 2015 babel - preset - react
webpack.config.js bable
{
test:/\.(jsx|js)$/,
use:{
loader:'babel-loader',
options:{
presets:[
"es2015","react"
]
}
},
exclude:/node_modules/
}
현재 인터넷 에 서 는 babel - preset - es 2015 가 유행 하지 않 습 니 다. 현재 공식 적 으로 추천 하 는 것 은 babel - preset - env 입 니 다.
npm install --save-dev babel-preset-env
새. babelrc 파일 을 만 듭 니 다. 안에 설정 하면 됩 니 다.
{
"presets":["react","env"]
}
기본 최종 웹 팩. config. js 설정
// webpack.config.js require, ;
const webpack = require('webpack');// webpack , plugins
const path = require('path');// node path (node path )
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');// JS , uglify
const HtmlWebpackPlugin = require('html-webpack-plugin');// html
const extractTextPlugin = require('extract-text-webpack-plugin');// css js , , css less
const glob = require('glob');// Node.js global;node glob * , glob ;https://blog.csdn.net/tangxiaolang101/article/details/53931145
const PurifyCSSPlugin = require('purifycss-webpack');//PurifyCSS CSS
// const entry = require(./webpack_config/entry_webpack.js);
// css
var website ={
publicPath:"http://localhost:5200/"
}
// if(process.env.type== "build"){
// var website={
// publicPath:"http://localhost:5200/"
// }
// }else{
// var website={
// publicPath:"http://localhost:5200/"
// }
// }
// console.log( encodeURIComponent(process.env.type));
module.exports = {
devtool: 'eval-source-map',
entry: {
main:'./src/js/index.js'
},
// entry:entry.path,
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath:website.publicPath// css publicPath;
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['env']
}
},
{
test: /\.css$/,
// use: [
// { loader: 'style-loader', options: { sourceMap: true } },
// { loader: 'css-loader' }
// ]
// css :
use: extractTextPlugin.extract({
use: [
{loader:'css-loader'},
{loader:'less-loader'}
],
fallback: "style-loader",
})
},
{
test:/\.(png|jpg|gif)/ ,
use:[{
loader:'url-loader',
options:{
limit:5000,
outputPath:'img/'//outputPath
}
}]
},
// html img 404
{
test: /\.(htm|html)$/i,
use:[ 'html-withimg-loader']
},
{
test: /\.less$/,
use: [
{loader: 'style-loader'},
{loader:'css-loader'},
{loader:'less-loader'}
]
},
{
test:/\.(jsx|js)$/,
use:{
loader:'babel-loader',
options:{
presets:[
"es2015","react"
]
}
},
exclude:/node_modules/
},
{
test:/\.(jsx|js)$/,
use:{
loader:'babel-loader',
},
exclude:/node_modules/
}
// {
// watchOptions:{
// // ,
// poll:1000,
// // 。 500 ,
// aggregateTimeout:500,
// //
// ignored:/node_modules/,
// }
// }
]
},
plugins: [
new UglifyJSPlugin(),
new extractTextPlugin('/css/index.css'),
new HtmlWebpackPlugin({
minify:{
removeAttributeQuotes:true
},
hash:true,
template:'./src/html/index.html',
filename:'html/index.html'
}),
new HtmlWebpackPlugin({
template:'./src/html/oop.html',
filename:'html/oop.html'
}),
new PurifyCSSPlugin({
// Give paths to parse for rules. These should be absolute!
paths: glob.sync(path.join(__dirname, 'src/*.html')), }),
// ProvidePlugin webpack , js
new webpack.ProvidePlugin({ $:"jquery" })
],
// JS ,
devServer: {
//
contentBase: "./dist",// || contentBase:path:path.resolve(__dirname,'dist')
// IP , IP localhost
host:'localhost',
//
compress:true,
//
port:5200,
historyApiFallback: true,//
inline: true//
}
};
pake.josn
{
"name": "md",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dv": "webpack --mode development",
"bd": "webpack --mode production",
"server": "webpack-dev-server --open"
},
"author": "",
"license": "ISC",
"dependencies": {
"html-withimg-loader": "^0.1.16",
"jquery": "^3.3.1",
"npm": "^6.0.1",
"to": "^0.2.9",
"update": "^0.7.4"
},
"devDependencies": {
"autoprefixer": "^8.5.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"less": "^3.0.4",
"less-loader": "^4.1.0",
"postcss-loader": "^2.1.5",
"purify-css": "^1.2.5",
"purifycss-webpack": "^0.7.0",
"style-loader": "^0.21.0",
"uglifyjs-webpack-plugin": "^1.2.5",
"url-loader": "^1.0.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4"
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.