programing

파일을 번들하지 않도록 웹 팩 가져오기

cafebook 2023. 3. 4. 15:10
반응형

파일을 번들하지 않도록 웹 팩 가져오기

그래서 현재 저는 웹 팩(.tsx 파일 구축 및 .html 파일 복사용)과 개발 서비스용 웹 팩-dev-server를 조합하여 사용하고 있는 프로토타입을 사용하고 있습니다.리액트와 리액트 DOM도 라이브러리의 의존관계로서 사용하고 있다고 가정할 수 있습니다.현재 빌드 출력은 다음과 같습니다.

dist
    -favicon.ico
    -index.html
    -main.js
    -main.js.map // for source-mapping between tsx / js files

그러면 모든 모듈이 배치됩니다(라이브러리의존관계도 포함).최종 결과는 다음과 같습니다.

dist
    -favicon.ico
    -index.html
    -appName.js
    -appName.min.js
    -react.js
    -react.min.js
    -reactDOM.js
    -reactDOM.min.js

index.html 내의 각 라이브러리와 .tsx 파일의 Import 문에 대한 참조가 있습니다.그래서 제 질문은...이 거대한 번들 .js 파일을 생성하는 웹 팩에서 개별 .js 파일(라이브러리 포함, 개별적으로 지정할 필요 없음)으로 이동하려면 어떻게 해야 합니까?**Bonus: prod/dev 환경 플래그를 작성하는 방법을 알고 있습니다.그러면 (다시 번들하지 않고) 개별 파일을 최소화하는 방법을 알려주세요.

현재 webpack.config:

var webpack = require("webpack"); // Assigning node package of webpack dependency to var for later utilization
var path = require("path"); // // Assigning node package of path dependency to var for later utilization

module.exports = {
    entry:  [
                "./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
                "./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
                "./wwwroot/favicon.ico" // Input location for favicon
            ],
    output: {
        path: "./dist/", // Where we want to host files in local file directory structure
        publicPath: "/", // Where we want files to appear in hosting (eventual resolution to: https://localhost:4444/)
        filename: "appName.js" // What we want end compiled app JS file to be called
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    devServer: {
        contentBase: './dist', // Copy and serve files from dist folder
        port: 4444, // Host on localhost port 4444
        // https: true, // Enable self-signed https/ssl cert debugging
        colors: true // Enable color-coding for debugging (VS Code does not currently emit colors, so none will be present there)
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [
            "",
            ".ico",
            ".js",
            ".ts",
            ".tsx",
            ".web.js",
            ".webpack.js"
        ]
    },

    module: {
        loaders: [
            // This loader copies the index.html file & favicon.ico to the output directory.
            {
                test: /\.(html|ico)$/,
                loader: 'file?name=[name].[ext]'
            },
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            {
                test: /\.tsx?$/,
                loaders: ["ts-loader"]
            }
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                test: /\.js$/,
                loader: "source-map-loader"
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    // externals: {
    //     "react": "React",
    //     "react-dom": "ReactDOM",
    //     "redux": "Redux"
    // }
};

를 변경하다output를 들어 이름 중심 설정입니다.

    entry: {
        dash: 'app/dash.ts',
        home: 'app/home.ts',
    },
    output: {
        path: './public',
        filename: 'build/[name].js',
        sourceMapFilename: 'build/[name].js.map'
    },

@basarat의 답변을 확장하려면glob"엔트리" 구성을 구축하기 위해 노드의 표준 라이브러리에서 패키지를 만듭니다.

const glob = require("glob");

module.exports = [
  {
    target: "node",
    entry: glob.sync("./src/**/*.test.{ts,tsx}").reduce((acc, file) => {
      acc[file.replace(/^\.\/src\//, "")] = file;
      return acc;
    }, {}),
    output: {
      filename: "[name].js",
      chunkFilename: "[name]-[id].js",
      path: __dirname + "/dist"
    },
    //...
  }
];

그러면 소스와 동일한 이름의 파일이 빌드되어 대체됩니다..ts그리고..tsx와 함께.js.

OPs 답변이 질문에서 복사되었습니다.

결국 제 요구에 맞는 솔루션을 찾게 되었습니다.다만, Web 팩에서는, 몇개의 추가 설정이 필요하게 되었습니다.그래도 좀 더 역동적으로 만들고 싶지만 나중에 완성될 것입니다.제가 찾던 해상도는 공통 모듈을 "chunk"할 수 있는 기능이었지만, 웹 팩에 제공되는 "entry" 포인트가 주어진 파일 이름이라고 했습니다.몇 개의 파일을 조합하는 것은 상관없지만, 이 프로젝트가 SPA(싱글 페이지 애플리케이션)가 아니기 때문에, 전체적인 파일이 컴포넌트 레벨로 되어 있으면 좋겠다고 생각했습니다.

추가 코드는 다음과 같습니다.

plugins: [
    new webpack.optimize.CommonsChunkPlugin({ // This plugin is for extracting and created "chunks" (extracted parts of the code that are common and aren't page specific)
        // One of these instances of plugins needs to be specified for EACH chunk file output desired
        filename: "common.js", // Filename for this particular set of chunks to be stored
        name: "common", // Entry point name given for where to pull all of the chunks
        minChunks: 3 // Minimum number of chunks to be created
    })
]

또한 react, react-dom 및 redux 모듈을 common.js 파일에 할당할 수 있도록 엔트리 포인트(예를 들어 아래 참조)를 변수 이름으로 파라미터화해야 했습니다.

entry:  {
    main:    "./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
    index:   "./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
    favicon: "./wwwroot/favicon.ico", // Input location for favicon
    common:  [ "react", "react-dom", "redux" ] // All of the "chunks" to extract and place in common file for faster loading of common libraries between pages
},

언급URL : https://stackoverflow.com/questions/40096470/get-webpack-not-to-bundle-files

반응형