简体   繁体   English

如何使用webpack在项目中设置多个文件入口和输出?

[英]How to set multiple file entry and output in project with webpack?

How to set multiple file entry/output in project with webpack?如何使用 webpack 在项目中设置多个文件输入/输出?

I follow http://webpack.github.io/docs/tutorials/getting-started/ success compile if only one file in one entry/output...如果一个条目/输出中只有一个文件,我按照http://webpack.github.io/docs/tutorials/getting-started/成功编译...

directory目录

app
webpack.config.js
./assets
././javascripts/Administrator/Article/Create/Base.js
././javascripts/Administrator/Article/Edit/Base.js
././javascripts/Account/Index/Base.js
././javascripts/Contact/Index/Base.js
...

how to output like this?如何输出这样的?

././javascripts/Administrator/Article/Create/bundle.js
././javascripts/Administrator/Article/Edit/bundle.js
././javascripts/Account/Index/bundle.js
././javascripts/Contact/Index/bundle.js

webpack.config.js webpack.config.js

module.exports = {
  entry: {
    'AdministratorArticleCreate':['./assets/javascripts/Administrator/Article/Create/Base.js']
  },
  output: {
    path: 
  }

    // if only one file
    // entry: "./assets/javascripts/Administrator/Article/Create/Base.js",
    // output: {
    //     // path: __dirname,
    //     path: "./assets/javascripts/Administrator/Article/Create/",
    //     filename: "bundle.js"
    // }
};

For many entry points use arrays as a value of entry property:对于许多入口点,使用数组作为entry属性的值:

entry: {
  app: ['./app/main.js', '.lib/index.js'],
  vendors: ['react']
}

app and vendors are arrays, so you can put there as many file paths as you need. appvendors是数组,因此您可以根据需要放置任意数量的文件路径。

For output case:对于输出情况:

output: {
  path: staticPath,
  filename: '[name].js'
}

The [name] is taken from entry properties, so if we have app and vendors as properties, we got 2 output files - app.js and vendors.js . [name]取自entry属性,因此如果我们将appvendors作为属性,我们将获得 2 个输出文件 - app.jsvendors.js

Documentation link 文档链接

If you want to output to multiple directories, you can use the path as the entry name.如果要输出到多个目录,可以使用路径作为条目名称。 For example if you want this directory structure:例如,如果你想要这个目录结构:

apps
├── dir1
│   └── js
│       ├── main.js [entry 1]
│       └── bundle.js [output 1]
└── dir2
    ├── index.js [entry 2]
    └── foo.js [output 2]

Then try this in your module.exports:然后在你的 module.exports 中试试这个:

{
  entry: {
    'dir1/js/bundle': path.resolve(__dirname, '/apps/dir1/js/main.js'),
    'dir2/foo' : path.resolve(__dirname, '/apps/dir2/index.js')
  },
  output: {
    path: path.resolve(__dirname, '/apps'),
    filename: '[name].js'
  },
  ...
}

what really solved it for me was this:真正为我解决的是:

entry:  {
    app : __dirname + "/app/views/app/app.js",
    admin : __dirname + "/app/views/admin/admin.js"
}

output: {
    path: __dirname + "/public",
    filename: "[name].js"
},

You can detect multiple entries and generate separate output files by using glob sync patterns.您可以使用全局同步模式检测多个条目并生成单独的输出文件。

Put this into your webpack.config.js (without the ... )把它放到你的webpack.config.js (没有...

const glob = require("glob");
...
module.exports = (env, options) => ({
  ...
  entry: glob.sync("./javascripts/**/*.js").reduce((acc, item) => {
    const path = item.split("/");
    path.pop();
    const name = path.join('/');
    acc[name] = item;
    return acc;
  }, {}),
  output: {
    filename: "[name]/bundle.js",
    path: path.resolve(__dirname, "")
  },
  ...
});

This "should" give you the desired output.这“应该”为您提供所需的输出。

What if you want to get output files as foo.css and bar.js at the same time?如果你想同时获得foo.cssbar.js输出文件foo.css bar.js the answers above seem incapable to handle this.上面的答案似乎无法处理这个问题。

The sane way is to use multi-compiler .明智的方法是使用multi-compiler One input file one config object one output file.一个输入文件一个配置对象一个输出文件。 From this answer .从这个答案

this webpack plugin web-webpack-plugin can resolve it in a sample way.这个 webpack 插件web-webpack-plugin可以通过示例方式解决它。

AutoWebPlugin can find all page entry in an directory,then auto config an WebPlugin for every page to output an html file,you can use it as below: AutoWebPlugin可以找到一个目录下的所有页面条目,然后为每个页面自动配置一个WebPlugin输出一个 html 文件,你可以使用它如下:

webpack config网络包配置

module.exports = {
    plugins: [
        new AutoWebPlugin(
            // the directory hold all pages
            './src/', 
            {
            // the template file path used by all pages
            template: './src/template.html',
            // javascript main file for current page,if it is null will use index.js in current page directory as main file
            entity: null,
            // extract common chunk for all pages and then put it into a file named common,if it is null then not do extract action
            // achieve by CommonsChunkPlugin
            commonsChunk: 'common',
            // pre append to all page's entry
            preEntrys:['./path/to/file1.js'],
            // post append to all page's entry
            postEntrys:['./path/to/file2.js'],
        }),
    ]
};

src directory源目录

── src
│   ├── home
│   │   └── index.js
│   ├── ie_polyfill.js
│   ├── login
│   │   └── index.js
│   ├── polyfill.js
│   ├── signup
│   │   └── index.js
│   └── template.html

output directory输出目录

├── dist
│   ├── common.js
│   ├── home.html
│   ├── home.js
│   ├── ie_polyfill.js
│   ├── login.html
│   ├── login.js
│   ├── polyfill.js
│   ├── signup.html
│   └── signup.js

AutoWebPlugin find all page home login signup directory in ./src/ ,for this three page home login signup will use index.js as main file and output three html file home.html login.html signup.html` AutoWebPlugin找到所有网页home login signup目录./src/ ,对于这三页home login signup将使用index.js作为主文件和输出了3个HTML文件home.html的login.html的signup.html`

see doc:auto detect html entry请参阅文档:自动检测 html 条目

This question is 2 years old so I think the author has almost certainly moved on from this issue, but to anyone landing here more recently I had a really similar need and was able to write my own plugin to allow for dynamic output paths/names from known and/or unknown entry points.这个问题已经有 2 年历史了,所以我认为作者几乎肯定已经从这个问题转向了,但是对于最近登陆这里的任何人,我有一个非常相似的需求,并且能够编写我自己的插件以允许动态输出路径/名称来自已知和/或未知的入口点。

My problem and thought process for the solution can be found here . 我的问题和解决方案的思考过程可以在这里找到

And the Node package itself here .和 Node 包本身在这里

For my use case I actually needed to use different templates based on environment.对于我的用例,我实际上需要根据环境使用不同的模板。 To achieve this I passed in the NODE_ENV variable为了实现这一点,我传入了 NODE_ENV 变量

module.exports = (env, argv) => {
  const ENVIRONMENT = env.NODE_ENV;
  let INDEX_HTML = 'index.html';
  if (ENVIRONMENT === 'staging') {
    INDEX_HTML = 'index-stg.html';
  }

Then:然后:

if (NODE_ENV === 'staging') {
   INDEX_HTML = 'index-stg.html';
}

In the output:在输出中:

output: {
      path: process.cwd() + '/build',
      filename: `[name].js`,
      chunkFilename: `[${HASH_MODE}].[name].js`
    },

plugins:插件:

new HtmlWebpackPlugin({
        inject: true,
        template: `app/${INDEX_HTML}`,
      }),

Using the following, I was able to get webpack to search for typescript and sass files.使用以下内容,我能够让 webpack 搜索打字稿和 sass 文件。

...
entry: glob
  .sync("./src/{sass,js}/**/*.{ts,scss}")
  .reduce(function (obj, el) {
    obj[path.parse(el).name] = el;
    return obj;
  }, {}),
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM