Webpack.config index.html을 dist 폴더에 복사하는 방법
/ dist로 들어가는 자산을 자동화하려고합니다. 다음과 같은 config.js가 있습니다.
module.exports = {
context: __dirname + "/lib",
entry: {
main: [
"./baa.ts"
]
},
output: {
path: __dirname + "/dist",
filename: "foo.js"
},
devtool: "source-map",
module: {
loaders: [
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
},
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
resolve: {
// you can now require('file') instead of require('file.js')
extensions: ['', '.js', '.json']
}
}
또한 webpack을 실행할 때 / lib 옆에있는 디렉토리의 / dist 폴더에 main.html을 포함하고 싶습니다. 어떻게해야합니까?
업데이트 1 2017_____________
내가 가장 좋아하는 방법 html-webpack-plugin
은 템플릿 파일과 함께 사용하는 것 입니다. 받아 들여진 답변 덕분에! 이 방법의 장점은 인덱스 파일에 캐시 된 js 링크가 상자에서 추가된다는 것입니다!
옵션 1
당신의에서 index.js
파일 (예 : 웹팩 항목)은 당신을 필요로 추가 index.html
를 통해 파일 로더 플러그인, 예를 들면 :
require('file-loader?name=[name].[ext]!../index.html');
webpack으로 프로젝트를 빌드 index.html
하면 출력 폴더에 있습니다.
옵션 2
index.html이 전혀 없도록 html-webpack-plugin 을 사용하십시오 . 간단히 웹팩이 파일을 생성하도록합니다.
VitalyB의 답변에 옵션을 추가하겠습니다.
옵션 3
npm을 통해. npm을 통해 명령을 실행하면 package.json 에이 설정 을 추가 할 수 있습니다 (webpack.config.js도 확인하십시오). run을 개발 npm start
하기 위해 웹 서버가 소스 파일 디렉토리에서 실행되고 bundle.js를 같은 위치에서 사용할 수 있기 때문에이 경우 index.html을 복사 할 필요가 없습니다 (bundle.js는 메모리에만 있지만 index.html과 함께있는 것처럼 사용할 수 있습니다). 프로덕션 실행 npm run build
을 위해 dist 폴더에는 bundle.js가 포함되어 있으며 아래에서 볼 수 있듯이 index.html은 오래된 cp 명령으로 복사됩니다.
"scripts": {
"test": "NODE_ENV=test karma start",
"start": "node node_modules/.bin/webpack-dev-server --content-base app",
"build": "NODE_ENV=production node node_modules/.bin/webpack && cp app/index.html dist/index.html"
}
업데이트 : 옵션 4
가 복사 웹팩 - 플러그인은 이에 설명 된대로 유래 답변
그러나 일반적으로 index.html과 같은 첫 번째 파일과 큰 이미지 또는 비디오와 같은 더 큰 자산을 제외하고 CSS, html, 이미지 등을 앱에 직접 require
포함하면 webpack이 파일을 포함합니다. (로더 및 플러그인으로 올바르게 설정 한 후).
CopyWebpackPlugin을 사용할 수 있습니다 . 다음과 같이 작동합니다.
module.exports = {
plugins: [
new CopyWebpackPlugin([{
from: './*.html'
}])
]
}
I would say the answer is: you can't. (or at least: you shouldn't). This is not what Webpack is supposed to do. Webpack is a bundler, and it should not be used for other tasks (in this case: copying static files is another task). You should use a tool like Grunt or Gulp to do such tasks. It is very common to integrate Webpack as a Grunt task or as a Gulp task. They both have other tasks useful for copying files like you described, for example, grunt-contrib-copy or gulp-copy.
For other assets (not the index.html
), you can just bundle them in with Webpack (that is exactly what Webpack is for). For example, var image = require('assets/my_image.png');
. But I assume your index.html
needs to not be a part of the bundle, and therefore it is not a job for the bundler.
You can add the index directly to your entry config and using a file-loader to load it
module.exports = {
entry: [
__dirname + "/index.html",
.. other js files here
],
module: {
rules: [
{
test: /\.html/,
loader: 'file-loader?name=[name].[ext]',
},
.. other loaders
]
}
}
This work well on Windows:
npm install --save-dev copyfiles
- In
package.json
I have a copy task :"copy": "copyfiles -u 1 ./app/index.html ./deploy"
This move my index.html from the app folder into the deploy folder.
To copy an already existing index.html
file into the dist
directory you can simply use the HtmlWebpackPlugin by specifying the source index.html
as a template.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
template: './path/to/index.html',
})
],
// ...
};
The created dist/index.html
file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script>
tags by webpack. Minification and further options can be configured and are documented on github.
To extend @hobbeshunter's answer if you want to take only index.html you can also use CopyPlugin, The main motivation to use this method over using other packages is because it's a nightmare to add many packages for every single type and config it etc. The easiest way is to use CopyPlugin for everything:
npm install copy-webpack-plugin --save-dev
Then
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyPlugin([
{ from: 'static', to: 'static' },
{ from: 'index.html', to: 'index.html', toType: 'file'},
]),
],
};
As you can see it copy the whole static folder along with all of it's content into dist folder. No css or file or any other plugins needed.
While this method doesn't suit for everything, it would get the job done simply & quickly.
I also found it easy and generic enough to put my index.html
file in dist/
directory and add <script src='main.js'></script>
to index.html
to include my bundled webpack files. main.js
seems to be default output name of our bundle if no other specified in webpack's conf file. I guess it's not good and long-term solution, but I hope it can help to understand how webpack works.
'Programming' 카테고리의 다른 글
ASP.Net MVC에서 컨트롤러에서 요청을 조롱하는 방법? (0) | 2020.05.27 |
---|---|
화살표 함수 (공개 클래스 필드)를 클래스 메서드로 사용하는 방법은 무엇입니까? (0) | 2020.05.27 |
가능한 두 테이블 중 하나에 MySQL 외래 키를 수행 할 수 있습니까? (0) | 2020.05.26 |
AngularJS는 jQuery보다 나은 점은 무엇입니까? (0) | 2020.05.26 |
Spring MVC : GET @RequestParam과 같은 복잡한 객체 (0) | 2020.05.26 |