Webpack配置 – 如何编译不同路径中的文件

huangapple go评论78阅读模式
英文:

Webpack Config - how can I compiler file in difference path

问题

我有

 - `./src` - 这是我的源文件index.htmlindex.tsstyle.scss
 - `./public` - 这是我的站点和编译器文件index.htmlbundle.jsstyle.css

我想要构建我的 `./src` 文件中的 `index.html`  `./public/`将我的 `index.ts` 构建到 `./public/success/script/index.js` `style.scss` 构建到 `./public/success/style/style.css` 举个例子

我应该如何做呢

`webpack.config.js`:

```js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: path.resolve(__dirname, './src/scripts/index.ts'),
    mode: "development",
    output: {
        path: path.resolve(__dirname, './public/'),
        filename: 'app.min.js',
    },
    devServer: {
        static:{
            directory: path.join(__dirname, './public')
        },
        port: 3000,
        open: true,
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.ts|.js$/,
                use: ["ts-loader"],
                exclude: /node_modules/,
            },
            {
                test: /\.scss$/,
                use:[
                    "sass-loader",
                    "style-loader",
                    "css-loader"
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './src/index.html'),
            filename: path.resolve(__dirname, "./public/index.html"),
            inject: "body"
        }),
    ],
};
英文:

I have

  • ./src - it's my source files (index.html, index.ts, style.scss)
  • ./public - my site and compiler files (index.html, bundle.js, style.css)

and I wanna build my ./src files index.html into ./public/, my index.ts into ./public/success/script/index.js, and style.scss into ./public/success/style/style.css for exemple

how can I do that?

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: path.resolve(__dirname, './src/scripts/index.ts'),
    mode: "development",
    output: {
        path: path.resolve(__dirname, './public/'),
        filename: 'app.min.js',
    },
    devServer: {
        static:{
            directory: path.join(__dirname,  './public')
        },
        port: 3000,
        open: true,
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.ts|.js$/,
                use: ["ts-loader"],
                exclude: /node_modules/,
            },
            {
                test: /\.scss$/,
                use:[
                    "sass-loader",
                    "style-loader",
                    "css-loader"
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './src/index.html'),
            filename: path.resolve(__dirname, "./public/index.html"),
            inject: "body"
        }),
    ],
};

答案1

得分: 0

请注意,以下是翻译好的部分:

See output.filename configuration, you are allowed to use something like 'js/[name]/bundle.js' to create a folder structure.
查看 output.filename 配置,你可以使用类似 'js/[name]/bundle.js' 这样的方式来创建文件夹结构。

The filename of MiniCssExtractPlugin works like output.filename.
MiniCssExtractPluginfilename 配置与 output.filename 类似。

In order to simplify the configuration, the following example does not use ts-loader and sass-loader as they do not affect the build output.
为了简化配置,以下示例不使用 ts-loadersass-loader,因为它们不会影响构建输出。

Project structure(after building):
构建后的项目结构:

$ tree -L 4 -I node_modules
.
├── package-lock.json
├── package.json
├── public
│   ├── index.html
│   └── success
│       ├── script
│       │   └── index.js
│       └── style
│           └── style.css
├── src
│   ├── index.html
│   ├── index.js
│   └── style.css
└── webpack.config.js

src/index.js:
src/index.js

import './style.css';

console.log('webpack mini template');

src/index.html:
src/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
</body>
</html>

src/style.css:
src/style.css

body {
	background: green;
}

webpack.config.js:
webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
	entry: path.resolve(__dirname, './src/index.js'),
	mode: 'development',
	output: {
		path: path.resolve(__dirname, './public/'),
		filename: 'success/script/index.js',
		clean: true,
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader'],
			},
		],
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: path.resolve(__dirname, './src/index.html'),
			inject: 'body',
		}),
		new MiniCssExtractPlugin({ filename: 'success/style/style.css' }),
	],
};

Build logs:
构建日志:

> webpack

asset success/script/index.js 3.23 KiB [emitted] (name: main)
asset index.html 357 bytes [emitted]
asset success/style/style.css 242 bytes [emitted] (name: main)
Entrypoint main 3.46 KiB = success/style/style.css 242 bytes success/script/index.js 3.23 KiB
orphan modules 2.76 KiB (javascript) 937 bytes (runtime) [orphan] 7 modules
runtime modules 274 bytes 1 module
cacheable modules 111 bytes (javascript) 29 bytes (css/mini-extract)
  ./src/index.js 61 bytes [built] [code generated]
  ./src/style.css 50 bytes [built] [code generated]
  css ./node_modules/css-loader/dist/cjs.js!./src/style.css 29 bytes [built] [code generated]
webpack 5.88.2 compiled successfully in 203 ms

Output:
输出:

public/index.html:
public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
<link href="success/style/style.css" rel="stylesheet"></head>
<body>
<script defer src="success/script/index.js"></script></body>
</html>

package.json:
package.json

{
	"version": "1.0.0",
	"scripts": {
		"build": "webpack"
	},
	"devDependencies": {
		"css-loader": "^6.8.1",
		"html-webpack-plugin": "^5.5.3",
		"mini-css-extract-plugin": "^2.7.6",
		"webpack": "^5.80.0",
		"webpack-cli": "^5.0.2"
	}
}
英文:

See output.filename configuration, you are allowed to use something like 'js/[name]/bundle.js' to create a folder structure.

The filename of MiniCssExtractPlugin works like output.filename.

In order to simplify the configuration, the following example does not use ts-loader and sass-loader as they do not affect the build output.

Project structure(after building):

$ tree -L 4 -I node_modules
.
├── package-lock.json
├── package.json
├── public
│   ├── index.html
│   └── success
│       ├── script
│       │   └── index.js
│       └── style
│           └── style.css
├── src
│   ├── index.html
│   ├── index.js
│   └── style.css
└── webpack.config.js

src/index.js:

import './style.css';

console.log('webpack mini template');

src/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
</body>
</html>

src/style.css:

body {
	background: green;
}

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
	entry: path.resolve(__dirname, './src/index.js'),
	mode: 'development',
	output: {
		path: path.resolve(__dirname, './public/'),
		filename: 'success/script/index.js',
		clean: true,
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader'],
			},
		],
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: path.resolve(__dirname, './src/index.html'),
			inject: 'body',
		}),
		new MiniCssExtractPlugin({ filename: 'success/style/style.css' }),
	],
};

Build logs:

> webpack

asset success/script/index.js 3.23 KiB [emitted] (name: main)
asset index.html 357 bytes [emitted]
asset success/style/style.css 242 bytes [emitted] (name: main)
Entrypoint main 3.46 KiB = success/style/style.css 242 bytes success/script/index.js 3.23 KiB
orphan modules 2.76 KiB (javascript) 937 bytes (runtime) [orphan] 7 modules
runtime modules 274 bytes 1 module
cacheable modules 111 bytes (javascript) 29 bytes (css/mini-extract)
  ./src/index.js 61 bytes [built] [code generated]
  ./src/style.css 50 bytes [built] [code generated]
  css ./node_modules/css-loader/dist/cjs.js!./src/style.css 29 bytes [built] [code generated]
webpack 5.88.2 compiled successfully in 203 ms

Output:

public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
<link href="success/style/style.css" rel="stylesheet"></head>
<body>
<script defer src="success/script/index.js"></script></body>
</html>

package.json:

{
	"version": "1.0.0",
	"scripts": {
		"build": "webpack"
	},
	"devDependencies": {
		"css-loader": "^6.8.1",
		"html-webpack-plugin": "^5.5.3",
		"mini-css-extract-plugin": "^2.7.6",
		"webpack": "^5.80.0",
		"webpack-cli": "^5.0.2"
	}
}

huangapple
  • 本文由 发表于 2023年7月31日 22:03:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定